1

I am using HttpURLConnection class to send Post request to my server but its not working, I did the same Post call using DefaultHttpClient & its work properly, but in android org.apache.http.impl.client.DefaultHttpClient is deprecated, that's why I am using HttpURLConnection class. I don't know is anything wrong with the way I am sending the JSON object or something else.

Below is my code implementation

URL url = new URL(linkPath);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(10000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));

            writer.close();
            out.close();
            urlConnection.disconnect();
AndroidDev
  • 4,521
  • 24
  • 78
  • 126
  • Take a look at the code in this question: http://stackoverflow.com/questions/21404252/post-request-send-json-data-java-httpurlconnection Note these lines: `con.setRequestProperty("Content-Type", "application/json");` and `con.setRequestProperty("Accept", "application/json");`, and the suggestion in the answer: `con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");` – Daniel Nugent Aug 06 '15 at 07:37
  • I tried setting both, but no luck. But why it is working when I used DefaultHttpClient. Although this is deprecated in android. – AndroidDev Aug 06 '15 at 07:43
  • Google decided to deprecate it, the developers at Apache are not happy about it. It seems it was a political decision more than anything. Nothing you can do but switch over to HttpURLConnection, which has been there the whole time (since API level 1), but nobody used to use it because the Apache classes were more straightforward. I'll take a look tomorrow and see if I can get a working implementation if this is still unanswered. – Daniel Nugent Aug 06 '15 at 07:50
  • Same problem here. I tried to send a jsonobject with HttpUrlConnection and the post is nothing. I crawl and found the post inside the system.web.httpvaluecollection, with no any key attached. I think that's why the controller didn't catch the post. – Buzz Sep 28 '15 at 10:30

0 Answers0