Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get body of Bad Request httpURLConnection.getInputStream()

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. :)
like image 657
Rez Avatar asked Feb 03 '14 11:02

Rez


People also ask

How do I get response body in HttpURLConnection?

To get the response body from a URL as a String, we should first create an HttpURLConnection using our URL: HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL). openConnection();

How do I get HttpURLConnection error message?

Java HttpURLConnection getErrorStream() Method This method is used to get an error stream if the connection is disconnected. This method does not set the connection. If the connection is not established or server does not cause any error during establishing the connection, then this method will return null.

How do I close HttpURLConnection?

If client does not call close() , call disconnect() will close the InputStream and close the Socket . So in order to reuse the Socket , just call InputStream. close() .


2 Answers

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

like image 98
hgoebl Avatar answered Oct 18 '22 20:10

hgoebl


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);
like image 23
Dhaval Jivani Avatar answered Oct 18 '22 20:10

Dhaval Jivani