为什么HttpURLConnection.getResponseCode()抛出IOException?
问题描述:
我可以看到,getResponseCode()
方法只是一个getter方法,它返回已经由之前发生的连接操作设置的statusCode
。为什么HttpURLConnection.getResponseCode()抛出IOException?
所以在这种情况下,为什么它会抛出一个IOException
?
我错过了什么?
答
从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;
}
...