<分区>
我可以看到 getResponseCode()
方法只是一个 getter 方法,它返回已经由之前发生的连接操作设置的 statusCode
。
那么在这种情况下,为什么会抛出 IOException
?
我错过了什么吗?
<分区>
我可以看到 getResponseCode()
方法只是一个 getter 方法,它返回已经由之前发生的连接操作设置的 statusCode
。
那么在这种情况下,为什么会抛出 IOException
?
我错过了什么吗?
最佳答案
来自 javadoc :
It will return 200 and 401 respectively. Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).
Returns: the HTTP Status-Code, or -1
Throws: IOException - if an error occurred connecting to the server.
意味着如果代码未知(尚未向服务器请求),连接将打开并完成(此时可能发生 IOException)。
如果我们查看源代码,我们有:
public int getResponseCode() throws IOException {
/*
* We're got the response code already
*/
if (responseCode != -1) {
return responseCode;
}
/*
* Ensure that we have connected to the server. Record
* exception as we need to re-throw it if there isn't
* a status line.
*/
Exception exc = null;
try {
getInputStream();
} catch (Exception e) {
exc = e;
}
/*
* If we can't a status-line then re-throw any exception
* that getInputStream threw.
*/
String statusLine = getHeaderField(0);
if (statusLine == null) {
if (exc != null) {
if (exc instanceof RuntimeException)
throw (RuntimeException)exc;
else
throw (IOException)exc;
}
return -1;
}
...
关于java - 为什么 HttpURLConnection.getResponseCode() 抛出 IOException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16332850/