在Java中,当HTTP结果为404范围时,此代码抛出异常:
URL url = new URL("http://stackoverflow.com/asdf404notfound");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); // throws!
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我碰巧知道内容是404,但我仍然想要阅读回复的主体.
(在我的实际情况中,响应代码是403,但响应正文解释了拒绝的原因,我想将其显示给用户.)
我如何访问响应正文?
我正在为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);
}
Run Code Online (Sandbox Code Playgroud)
我想测试如果身份验证失败会发生什么.但是,如果身份验证失败,在调用getInputStreamHttpURLConnection时,我直接得到一个IOException,说服务器响应401.我想如果服务器响应某些东西,无论成功或失败,它应该能够读取服务器返回的任何内容.我确信在这种情况下服务器会返回正文中的一些文本,因为如果我GET使用curl对服务器执行操作并且身份验证失败,我会获得一个JSON对象作为响应正文,其中包含一些错误消息.
有没有办法仍然得到响应机构即使401?