LHA
LHA

Reputation: 9655

Does java.net.HttpUrlConnection always throw IOException if there is an error status return by Server?

I am using java.net.HttpUrlConnection to make Http requests to my Server. I realized that if the Server return an error status (400 for example). HttpUrlConnection will throw an IOException corresponding to the error status.

My question is: Does HttpUrlConnection always throw an IOException if the server return an error status (4xx, 5xx)?

I take a look at HttpUrlConnection API description but I couldn't answer my question.

Updated: Please see my test:

public static void main(String[] args) {
    try {
        
        String url = "https://www.googleapis.com/oauth2/v3/userinfo?access_token=___fake_token";
        HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
        
        conn.getResponseCode();
        conn.getInputStream();
        
    } catch (Exception ex) {
        ex.printStackTrace();
        // Print IOException: java.io.IOException: Server returned HTTP response code: 401 for URL: https://www.googleapis.com/oauth2/v3/userinfo?access_token=abc

        // If I commented conn.getResponseCode() -> The same IOException
    }
}

Thank you!

Upvotes: 2

Views: 4155

Answers (2)

gavenkoa
gavenkoa

Reputation: 48873

In case of codes beyond 400 you need to call HttpURLConnection.getErrorStream() instead of HttpURLConnection.getInputStream(). Java 11 implementation:

public InputStream getErrorStream() {
    if (this.connected && this.responseCode >= 400) {
        if (this.errorStream != null) {
            return this.errorStream;
        }
        if (this.inputStream != null) {
            return this.inputStream;
        }
    }
    return null;
}

Upvotes: 0

user207421
user207421

Reputation: 310985

Not if you check getResponseCode() before getInputStream() and the problem is an HTTP return code rather than a connect error.

Upvotes: 7

Related Questions