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

扶醉桌前 提交于 2019-12-04 06:02:08

问题


I am using java.net.HttpUrlConnection to make Http request 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!


回答1:


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



来源:https://stackoverflow.com/questions/36381353/does-java-net-httpurlconnection-always-throw-ioexception-if-there-is-an-error-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!