Java HttpURLConnection.getInputStream but get 401 IOException

I am writing a REST client for CouchDB in Java. The following code should be pretty standard:

this.httpCnt.connect(); Map<String, String> responseHeaders = new HashMap<>(); int i = 1; while (true){ String headerKey = this.httpCnt.getHeaderFieldKey(i); if (headerKey == null) break; responseHeaders.put(headerKey, this.httpCnt.getHeaderField(i)); i++; } InputStreamReader reader = new InputStreamReader(this.httpCnt.getInputStream()); StringBuilder responseBuilder = new StringBuilder(); char[] buffer = new char[1024]; while(true){ int noCharRead = reader.read(buffer); if (noCharRead == -1){ reader.close(); break; } responseBuilder.append(buffer, 0, noCharRead); } 

I want to check what happens if the authentication fails. However, if authentication fails, when I call getInputStream HttpURLConnection, I get an IOException directly telling the responses of the 401 server. I believe that if the server responds to something, regardless of success or failure, it should be able to read everything that the server returns. And I'm sure that in this case the server really returns some text in the body, because if I do a GET on the server using curl and authentication fails, I get a JSON object as the response body with some error messages in it .

Is there a way to get the response body, even if 401?

+6
source share
2 answers

See this question :

"The HttpURLConnection.getErrorStream method returns an InputStream that can be used to extract data from error conditions (for example, 404), according to javadocs."

+12
source

You need to check the status of http with getResponseCode() to decide whether to use getInputStream() or getErrorStream() . In this case, you need to read the error stream.

+16
source

All Articles