问题描述
我可以看到getResponseCode()
方法只是一个getter方法,该方法返回已经由之前发生的connect操作设置的statusCode
.
I can see that getResponseCode()
method is just a getter Method that returns the statusCode
already set by the a connect action that happened before.
那么在这种情况下为什么会抛出IOException
?
我想念什么吗?
So in this context why does it throw an IOException
?
Am i missing something?
推荐答案
来自 javadoc :
返回:HTTP状态码或-1
Returns: the HTTP Status-Code, or -1
抛出: IOException-如果连接到服务器时发生错误.
Throws: IOException - if an error occurred connecting to the server.
表示如果代码未知(尚未向服务器请求),则打开连接并完成连接(此时可能会发生IOException).
Meaning if the code isn't yet known (not yet requested to the server) the connections is opened and connection done (at this point IOException can occur).
如果我们看一下源代码,就会发现:
If we take a look into the source code we have:
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;
}
...
这篇关于为什么HttpURLConnection.getResponseCode()引发IOException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!