Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

httpresponse - Java HttpURLConnection.getInputStream but get 401 IOException

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...