Why does HttpURLConnection.getResponseCode() throws IOException?

vivek_jonam picture vivek_jonam · May 2, 2013 · Viewed 8.7k times · Source

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?

Answer

Francisco Spaeth picture Francisco Spaeth · May 2, 2013

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