Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 656
vivek_jonam Avatar asked May 02 '13 07:05

vivek_jonam


1 Answers

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;
    }
    ...
like image 167
Francisco Spaeth Avatar answered Oct 21 '22 04:10

Francisco Spaeth