Java HttpURLConnection.getInputStream but get 401 IOException
Asked Answered
I

2

11

I am writing a REST client for CouchDB in Java. The following code should be quite 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 test what happen if the authentication fails. However if the authentication fails, when calling getInputStream of the HttpURLConnection, I get directly an IOException saying the server responses 401. I suppose if the server responses something, no matter success or failure, it should be able to read whatever the server returns. And I am sure in this case the server does return some text in the body, since if I do a GET to the server using curl and the authentication fails, I get a JSON object as the response body with some error messages in it.

Is there any way to still get the response body even if 401?

Isoclinal answered 11/5, 2014 at 13:56 Comment(1)
You could repalce the while with for loops to make the code more readableSpinster
S
16

See this question:

"The HttpURLConnection.getErrorStream method will return an InputStream which can be used to retrieve data from error conditions (such as a 404), according to the javadocs."

Spinster answered 11/5, 2014 at 14:5 Comment(0)
L
26

You need to check for the http status using getResponseCode() to decide if you should use getInputStream() or getErrorStream(). In this case, you need to read the error stream.

Laissezfaire answered 11/5, 2014 at 14:4 Comment(2)
Thanks! I would accept your reply as answer, but there can be only one answer possible...Isoclinal
OK, given the error code, how do you then decide which stream to use?Janayjanaya
S
16

See this question:

"The HttpURLConnection.getErrorStream method will return an InputStream which can be used to retrieve data from error conditions (such as a 404), according to the javadocs."

Spinster answered 11/5, 2014 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.