如果服务器返回错误状态,java.net.HttpUrlConnection是否总是抛出IOException? [英] Does java.net.HttpUrlConnection always throw IOException if there is an error status return by Server?

查看:175
本文介绍了如果服务器返回错误状态,java.net.HttpUrlConnection是否总是抛出IOException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java.net.HttpUrlConnection 使Http请求到我的服务器。我意识到如果服务器返回错误状态(例如400)。 HttpUrlConnection将抛出与错误状态相对应的IOException。

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.

我的问题是:如果服务器返回错误状态,HttpUrlConnection总是会抛出IOException(4xx,5xx )?

我来看看 HttpUrlConnection API描述,但我无法回答我的问题。

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

更新:请看到我的测试:

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

谢谢!

推荐答案

如果您在 getInputStream()之前检查 getResponseCode() ,问题是HTTP返回代码而不是连接错误。

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

这篇关于如果服务器返回错误状态,java.net.HttpUrlConnection是否总是抛出IOException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆