20

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. :)
1
  • In which way do you deserialize the JSON objects? Do you use org.json or Jackson or Gson?
    – hgoebl
    Feb 3, 2014 at 14:16

3 Answers 3

52

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

4
  • That is so true! Everybody says HttpURLConnection does not support it but it indeed does with getErrorStream(). Jun 5, 2015 at 14:52
  • 3
    In my case HttpURLConnection.getErrorStream() also returns null and when I do HttpURLConnection.getInputStream(), it thoriws IOException !! Can you help me to figure out what could be the case ? I have exactly the same code that is mentioned above in question. I am sending post request. May 13, 2016 at 17:19
  • What is your response-code? Can you simulate the request to the server with some REST-tool (postman) or cURL? Maybe it'd be better to ask a new question then.
    – hgoebl
    May 14, 2016 at 6:57
  • @shkschneider Who was this "Everybody" and why did he brazenly lie to you? :) Sep 19, 2022 at 13:04
16

you can get body of Bad Request in HttpURLConnection using this code :

InputStream errorstream = connection.getErrorStream();

String response = "";

String line;

BufferedReader br = new BufferedReader(new InputStreamReader(errorstream));

while ((line = br.readLine()) != null) {
    response += line;
}

Log.d("body of Bad Request HttpURLConnection", "Response: " + response);
1
  • 1
    Thanks for the explanation! Everyone keeps saying use getErrorStream(), but completely forgot that I had to "read" the error stream like the input stream - can be very tricky for the newbies.
    – Islam
    Mar 8, 2016 at 7:01
1

Use Apache Httpclient:

        String url = "http://192.168.1.6:7003/life/lifews/getFirstInstallment.html?rootPolicyNo=1392/2126/2/106/9995/1904&token=1984";
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);

        // add request header
        HttpResponse response = client.execute(request);
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println(result);
1
  • 2
    This is more of an alternative answer because it doesn't use HttpURLConnection like OP is using. Aug 6, 2020 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.