为什么HttpURLConnection.getResponseCode()会抛出IOException?

viv*_*nam 5 java urlconnection httpresponse httpurlconnection http-response-codes

我可以看到该getResponseCode()方法只是一个getter方法,它返回statusCode之前发生的连接操作已经设置的方法.

所以在这种情况下为什么会抛出一个IOException
我错过了什么吗?

Fra*_*eth 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;
    }
    ...
Run Code Online (Sandbox Code Playgroud)