asthiwanka
asthiwanka

Reputation: 447

Get the useful data sent from server in InputStream returned by getErrorStream in HttpURLConnection

When I invoke the getInputStream() method in HttpURLConnection, it returns an HTTP exception and I use this strategy to catch that exception.

try {
   con.getInputStream();
} catch (IOException e) {
   resStream = con.getErrorStream();
}

But, I need to get the useful data sent to resStream by the server as the JavaDoc states as follows. "Returns the error stream if the connection failed but the server sent useful data nonetheless."

Is there any way to get the response message (if the returned value is not null and there is a valid response returned) from the InputStream returned from the getErrorStream()?

Upvotes: 0

Views: 534

Answers (1)

wawlian
wawlian

Reputation: 46

You can wrap this byte stream to character stream and just read the error info.

InputStreamReader isr = new InputStreamReader(resStream);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
String line = null;
while((line = buf.readLine()) != null) {
    buf.append(line);
}
//assume you have a log object, you'd better not use System.out.println()
log.error(buf.toString());
//do not forget to close all the stream

Then, you can get stack trace from the server side. I hope this will help.

Upvotes: 1

Related Questions