问题描述
即使状态已知,HttpURLConnection.getResponseCode()
怎么抛出IOException
?
How come HttpURLConnection.getResponseCode()
throws IOException
even if the status is known?
Caused by: java.io.IOException: Server returned HTTP response code: 412 for URL: <my url>
获取响应代码不是问题,因为它是在异常消息中编写的.
It's not a problem of getting the response code because it is written in the exception message.
我希望可以有一个选择来获取状态代码(即使不是200左右),而不会出现异常,因此我可以在代码中决定要怎么做.
I would expect to have an option to get the status code (even if it's not ~200) without getting an exception, so I'll be able to decide in my code what to do.
完整堆栈跟踪:
Caused by: java.io.IOException: Server returned HTTP response code: 412 for URL: <my url>
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
... my code
更新我将服务器端实现更改为返回不同的状态码(303),并且现在可以正常工作(不抛出IOException).意思是它与412特别相关.
UPDATEI changed the server side implementation to return a different status code (303), and it's working now (not throwing IOException). Meaning it is specifically related to 412.
推荐答案
注意:这可能取决于您正在运行的JVM版本!,因为@SotiriosDelimanolis的测试给出了不同的结果
ATTENTION: this may depend on the JVM version you are running!!! as tests of @SotiriosDelimanolis gave different results
答案在HttpURLConnection的源代码中,并且与所有具有错误代码>的错误有关. 400
The answer is in the source code of the HttpURLConnection and is related to all the errors that have error code > 400
如果错误代码等于404或410,则会抛出FileNotFoundException,否则将引发IOException
If error code is equal 404 or 410 a FileNotFoundException is thrown else an IOException as
if (respCode >= 400) {
if (respCode == 404 || respCode == 410) {
throw new FileNotFoundException(url.toString());
} else {
throw new java.io.IOException("Server returned HTTP" +
" response code: " + respCode + " for URL: " +
url.toString());
}
}
sun.net.www.protocol.http.HttpURLConnection 1625行的源代码:
sun.net.www.protocol.http.HttpURLConnection Source code at line 1625:
我在 http://media.jarnbjo.de/412.php 上的测试使用:
Java(TM)SE运行时环境(内部版本1.7.0_21-b11)Java HotSpot(TM)64位服务器VM(内部版本23.21-b01,混合模式)
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)
在Windows 64位上
on Windows 64 bit
这篇关于已知代码时,HttpURLConnection.getResponseCode()引发IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!