问题描述
我正在使用 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 )?
我来看看 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()之前检查
,问题是HTTP返回代码而不是连接错误。 getResponseCode()
Not if you check getResponseCode()
before getInputStream()
and the problem is an HTTP return code rather than a connect error.
这篇关于如果服务器返回错误状态,java.net.HttpUrlConnection是否总是抛出IOException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!