javaexceptionhttpurlconnectionhttp-status-codes

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!


Solution

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