【发布时间】:2013-04-26 07:39:03
【问题描述】:
我可以看到getResponseCode() 方法只是一个getter 方法,它返回已经由之前发生的连接操作设置的statusCode。
那么在这种情况下,为什么它会抛出IOException?
我错过了什么吗?
【问题讨论】:
标签: java httpresponse httpurlconnection urlconnection http-response-codes
我可以看到getResponseCode() 方法只是一个getter 方法,它返回已经由之前发生的连接操作设置的statusCode。
那么在这种情况下,为什么它会抛出IOException?
我错过了什么吗?
【问题讨论】:
标签: java httpresponse httpurlconnection urlconnection http-response-codes
来自javadoc:
它将分别返回 200 和 401。如果无法从响应中识别出任何代码(即响应不是有效的 HTTP),则返回 -1。
返回: HTTP 状态码,或 -1
抛出: IOException - 如果连接到服务器时发生错误。
意味着如果代码未知(尚未向服务器请求),则打开连接并完成连接(此时可能发生 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;
}
...
【讨论】: