1

Please I have gone through all the question from stackoverflow, but those are not applicable to my problem.

enter image description here Please have look in image request working fine from POSTMAN.

But When I tried from android code it is not working. My Sample Android code is here.

@Override
        protected String doInBackground(Void... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {
                URL url = new URL("sample url");

                String postData = "key1=valu1&key2=valu2";

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(55000 /* milliseconds */);
                conn.setConnectTimeout(55000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os));
                writer.write(postData);

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(
                            new InputStreamReader(
                                    conn.getInputStream()));
                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {
                        Log.e("response ",line);
                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            } catch (Exception e) {
                Log.e("PlaceholderFragment", "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {

                    }
                }
            }
        }

Above java code return 405 error code. I also tried from OkHttp also. Please help.

Maheshwar Ligade
  • 6,171
  • 3
  • 35
  • 53

2 Answers2

2

Putting a '/' at the end of URL causes the redirect to happen because your server likes urls that end in '/'. POST is fully supported by the URL your server redirects you to, but the client is executing a GET request when it behaves according to your setRedirecting() call (cURL does the same exact thing with the -L switch) The fix is to either put a '/' at the end of URL, or to grab the Location header from the response yourself and then initiate another POST request manually.

This can be observed in wireshark. You can test the theory by trying to perform a GET request with your browser to the URL with a slash appended to it. That will cause the browser to get a 405. Here's the fixed code for Android, this code uses the simple fix of appending a '/' to the URL (not production ready):

Read more from here.

Do let me know if this helps :)

Additionally, try using this piece of code:

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://your URL");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
} 
Community
  • 1
  • 1
Han
  • 501
  • 6
  • 15
0

Your API call is reciveving data in GET parameter. So data should send along with url as given below

            String postData = Uri.encode("key1=valu1&key2=valu2");
            URL url = new URL("sample url"+"?+postData);
Sangeet Suresh
  • 2,309
  • 15
  • 19