Parse JSON from HttpURLConnection object Parse JSON from HttpURLConnection object json json

Parse JSON from HttpURLConnection object


You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {    HttpURLConnection c = null;    try {        URL u = new URL(url);        c = (HttpURLConnection) u.openConnection();        c.setRequestMethod("GET");        c.setRequestProperty("Content-length", "0");        c.setUseCaches(false);        c.setAllowUserInteraction(false);        c.setConnectTimeout(timeout);        c.setReadTimeout(timeout);        c.connect();        int status = c.getResponseCode();        switch (status) {            case 200:            case 201:                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));                StringBuilder sb = new StringBuilder();                String line;                while ((line = br.readLine()) != null) {                    sb.append(line+"\n");                }                br.close();                return sb.toString();        }    } catch (MalformedURLException ex) {        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);    } catch (IOException ex) {        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);    } finally {       if (c != null) {          try {              c.disconnect();          } catch (Exception ex) {             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);          }       }    }    return null;}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {    private int code;    private String message;    public int getCode() {        return code;    }    public void setCode(int code) {        this.code = code;    }    public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards


Define the following function (not mine, not sure where I found it long ago):

private static String convertStreamToString(InputStream is) {BufferedReader reader = new BufferedReader(new InputStreamReader(is));StringBuilder sb = new StringBuilder();String line = null;try {    while ((line = reader.readLine()) != null) {        sb.append(line + "\n");    }} catch (IOException e) {    e.printStackTrace();} finally {    try {        is.close();    } catch (IOException e) {        e.printStackTrace();    }}return sb.toString();

}

Then:

String jsonReply;if(conn.getResponseCode()==201 || conn.getResponseCode()==200)    {        success = true;        InputStream response = conn.getInputStream();        jsonReply = convertStreamToString(response);        // Do JSON handling here....    }


In addition, if you wish to parse your object in case of http error (400-5** codes),You can use the following code: (just replace 'getInputStream' with 'getErrorStream':

    BufferedReader rd = new BufferedReader(            new InputStreamReader(conn.getErrorStream()));    StringBuilder sb = new StringBuilder();    String line;    while ((line = rd.readLine()) != null) {        sb.append(line);    }    rd.close();    return sb.toString();