I am trying to send a Json object to my web server with and android application. Each example I find uses the HttpClient that has been removed by android 6. Please can someone give me an example of the HttpURLConnection method.
Asked
Active
Viewed 2,515 times
1
-
Why don't you just use Retrofit HTTP client and save yourself of all the troubles ? – Tosin Onikute Oct 10 '16 at 21:11
-
Note: Not an Android problem, but better libraries do exist. Volley and OkHttp are the most popular – OneCricketeer Oct 10 '16 at 21:21
-
1And another one. http://stackoverflow.com/questions/21404252/post-request-send-json-data-java-httpurlconnection – OneCricketeer Oct 10 '16 at 21:22
1 Answers
0
Here's an example of how you can use HttpURLConnection:
JSONObject json = getJSONData();
String targetURL = getTargetURL();
HttpURLConnection con = (HttpURLConnection)new URL(targetURL).openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setChunkedStreamingMode(0);
StringBuilder output = new StringBuilder();
output.append("data=");
output.append(URLEncoder.encode(data.get(json.toString()), "UTF-8"));
BufferedOutputStream stream = new BufferedOutputStream(con.getOutputStream());
stream.write(output.toString().getBytes());
out.flush();
con.connect();
Exception result = null;
int responseCode = con.getResponseCode();
switch(responseCode) {
case 200: //all ok
break;
case 401:
case 403:
// authorized
break;
default:
//whatever else...
String httpResponse = con.getResponseMessage();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String line;
try {
while ((line = br.readLine()) != null) {
Log.d("error", " " + line);
}
}
catch(Exception ex) {
//nothing to do here
}
break;
}
con.disconnect();
That said, you should seriously consider using an existing library, which will hide most of these from you.

Aleks G
- 56,435
- 29
- 168
- 265
-
I have read of Ion and Volley but not sure which to use or to learn to move forward. Can you please advice me on one to learn for the future? – master Oct 10 '16 at 21:56