Java HttpURLConnection.getInputStream 但得到 401 IOException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23593486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java HttpURLConnection.getInputStream but get 401 IOException
提问by Weixiang Guan
I am writing a REST client for CouchDB in Java. The following code should be quite standard:
我正在用 Java 为 CouchDB 编写 REST 客户端。以下代码应该是非常标准的:
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.
我想测试如果身份验证失败会发生什么。但是,如果身份验证失败,在调用getInputStream
HttpURLConnection 时,我会直接收到一个 IOException,说明服务器响应 401。我想如果服务器响应某些内容,无论成功还是失败,它都应该能够读取服务器返回的任何内容。而且我确信在这种情况下服务器确实会在正文中返回一些文本,因为如果我GET
使用 curl 对服务器执行 a并且身份验证失败,我会得到一个 JSON 对象作为响应正文,其中包含一些错误消息。
Is there any way to still get the response body even if 401?
即使 401,有没有办法仍然获得响应正文?
采纳答案by user3001
See this question:
看到这个问题:
"The HttpURLConnection.getErrorStreammethod will return an InputStream which can be used to retrieve data from error conditions (such as a 404), according to the javadocs."
“根据 javadocs,HttpURLConnection.getErrorStream方法将返回一个 InputStream,可用于从错误条件(例如 404)中检索数据。”
回答by Zavior
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.
您需要检查 http 状态getResponseCode()
以决定是否应该使用getInputStream()
或getErrorStream()
。在这种情况下,您需要读取错误流。