我可以看到getResponseCode()
方法只是一个getter方法,它返回之前发生的连接操作已设置的statusCode
。
所以在这种情况下为什么它会抛出IOException
?
我错过了什么吗?
答案 0 :(得分:6)
来自javadoc:
它将分别返回200和401。如果无法从响应中识别出代码,则返回-1(即,响应不是有效的HTTP)。
返回: 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;
}
...