1

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.

master
  • 374
  • 2
  • 4
  • 16

1 Answers1

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