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. :)
Rez
  • 470
  • 2
  • 8
  • 14
  • In which way do you deserialize the JSON objects? Do you use `org.json` or Jackson or Gson? – hgoebl Feb 03 '14 at 14:16

3 Answers3

52

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

hgoebl
  • 12,637
  • 9
  • 49
  • 72
  • That is so true! Everybody says HttpURLConnection does not support it but it indeed does with `getErrorStream()`. – shkschneider Jun 05 '15 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. – Tushar J Dudhatra May 13 '16 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 '16 at 06:57
  • @shkschneider Who was this "Everybody" and why did he brazenly lie to you? :) – The incredible Jan Sep 19 '22 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);
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Dhaval Jivani
  • 9,467
  • 2
  • 48
  • 42
  • 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 08 '16 at 07: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);
vahid kh
  • 1,874
  • 2
  • 12
  • 16