Why does HttpURLConnection.getResponseCode() throws IOException? [duplicate]

强颜欢笑 提交于 2019-12-07 04:08:23

问题


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.

So in this context why does it throw an IOException?
Am i missing something?


回答1:


From javadoc:

It will return 200 and 401 respectively. Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).

Returns: the HTTP Status-Code, or -1

Throws: IOException - if an error occurred connecting to the server.

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;
    }
    ...


来源:https://stackoverflow.com/questions/16332850/why-does-httpurlconnection-getresponsecode-throws-ioexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!