Parsing JSON from an HttpURLConnection Object

I am performing a basic HTTP authenticator with an HttpURLConnection object in Java.

  URL urlUse = new URL(url); HttpURLConnection conn = null; conn = (HttpURLConnection) urlUse.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-length", "0"); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); conn.connect(); if(conn.getResponseCode()==201 || conn.getResponseCode()==200) { success = true; } 

I expect a JSON object or string data in the format of a valid JSON or HTML object with plain text that is valid JSON. How to access this from HttpURLConnection after response?

+49
java json html parsing
May 08 '12 at 2:37
source share
5 answers

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

 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 the returned string with Google Gson to map JSON to an object of the specified class, for example:

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

There is a sample 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; } } 

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

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

Hello

+94
May 8 '12 at 3:24
source

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.... } 
+9
May 08 '12 at 2:48
source

The JSON string will only be the body of the response that you are returning from the URL you called. So add this code

 ... BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); 

This will let you see how JSON returns to the console. The only missing element you have is to use the JSON library to read this data and provide you with a Java view.

Here is an example using JSON-LIB

+2
May 08 '12 at 14:48
source

In addition, if you want to analyze your object in case of an HTTP error (codes 400-5 **), 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(); 
+2
Jun 16 '14 at 11:58 a.m.
source

This function will be used to retrieve data from the URL as an HttpResponse object.

 public HttpResponse getRespose(String url, String your_auth_code){ HttpClient client = new DefaultHttpClient(); HttpPost postForGetMethod = new HttpPost(url); postForGetMethod.addHeader("Content-type", "Application/JSON"); postForGetMethod.addHeader("Authorization", your_auth_code); return client.execute(postForGetMethod); } 

The function above is called here, and we get a json string form using the Apache Class library. And in the following statements, we are trying to make a simple pojo from the json we got.

 String jsonString = EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/ blah","Your_auth_if_you_need_one").getEntity(), "UTF-8"); final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new CustomJsonDeserialiser()); final Gson gson = gsonBuilder.create(); JsonElement json = new JsonParser().parse(jsonString); JsonJavaModel pojoModel = gson.fromJson( jsonElementForJavaObject, JsonJavaModel.class); 

This is a simple java model class for json input. public class JsonJavaModel {String content; Line header; } This is a custom deserializer:

 public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel> { @Override public JsonJavaModel deserialize(JsonElement json, Type type, JsonDeserializationContext arg2) throws JsonParseException { final JsonJavaModel jsonJavaModel= new JsonJavaModel(); JsonObject object = json.getAsJsonObject(); try { jsonJavaModel.content = object.get("Content").getAsString() jsonJavaModel.title = object.get("Title").getAsString() } catch (Exception e) { e.printStackTrace(); } return jsonJavaModel; } 

Include the Gson library and org.apache.http.util.EntityUtils;

+1
May 13 '15 at 11:48
source



All Articles