Why does HttpURLConnection.getResponseCode() throw

2019-04-29 11:21发布

问题:

This question already has an answer here:

  • HttpURLConnection.getResponseCode() throws IOException when code is known 2 answers

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