Saturday, January 9, 2016

Example on working with JSON and HttpURLConnection in Android

Hello Readers,

The new Android platforms use a class called HttpUrlConnection to work with external service calls,
This post is on a method which can send a JSON as body and receive a JSON as response you can use this method whenever you need to post a JSON to a rest location and get a json from a rest location.
This method will send the JSON string as the body of the request.

You'll have to pass the following
URL : the request url
JSON : the json to be sent can be NULL on get scenarios
Timeout : Connection timeout
Method : Http method POST / GET / PUT etc

public static String getJSON(String url, String json, int timeout, String method) {
    HttpURLConnection connection = null;
    try {

        URL u = new URL(url);
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod(method);
        
        //set the sending type and receiving type to json
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        connection.setAllowUserInteraction(false);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);

        if (json != null) {
            //set the content length of the body
            connection.setRequestProperty("Content-length", json.getBytes().length + "");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            //send the json as body of the request
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(json.getBytes("UTF-8"));
            outputStream.close();
        }

        //Connect to the server
        connection.connect();

        int status = connection.getResponseCode();
        Log.i("HTTP Client", "HTTP status code : " + status);
        switch (status) {
            case 200:
            case 201:
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                bufferedReader.close();
                Log.i("HTTP Client", "Received String : " + sb.toString());
                //return received string
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } catch (IOException ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } catch (Exception ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception ex) {
                Log.e("HTTP Client", "Error in http connection" + ex.toString());
            }
        }
    }
    return null;
}


Happy Coding
-Guru-

5 comments:

  1. Hi Guru,

    It is working like a charm.
    Thank you for sharing code.

    ReplyDelete
  2. looks like a bug that utf-8 is not used when estimating bytes but when sending

    connection.setRequestProperty("Content-length", json.getBytes().length + "");
    outputStream.write(json.getBytes("UTF-8"));

    ReplyDelete
  3. God bless you son, a simple, to the point, no frills code that runs. Seriously, you're a life saver, well done!

    ReplyDelete
  4. Ditto Tiago Seiler's comment. Thank you for this solution!

    ReplyDelete