Get body of Bad Request httpURLConnection.getInputStream()

Mohammad reza Khodabandeh picture Mohammad reza Khodabandeh · Feb 3, 2014 · Viewed 10.7k times · Source

I've been working on a portlet that calls Rest API. When the API is called and the requested data doesn't exist, it returns an appropriate error message in JSON format (with Bad request http code - 400), and if the id exists, it returns the requested data in json (with code 200).

How can I get the body of response (that contains error description) because invoking httpConn.getInputStream() method throws exception in case the response is bad request error.

Code:

HttpURLConnection httpConn = null;
URL url = new URL("http://192.168.1.20/personinfo.html?id=30");   
URLConnection connection = url.openConnection();
httpConn = (HttpURLConnection) connection;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("charset", "utf-8");
BufferedReader br = null;
if (!(httpConn.getResponseCode() == 400)) {
     br = new BufferedReader(new InputStreamReader((httpConn.getInputStream())));
     String output;
     StringBuilder builder = new StringBuilder();
     System.out.println("Output from Server .... \n");
     while ((output = br.readLine()) != null) 
          builder.append(output);
     return builder.toString();
}else
   here should catch the error message. :)

Answer

hgoebl picture hgoebl · Feb 3, 2014

In case of non-successful response codes, you have to read the body with HttpURLConnection.getErrorStream().