对于不存在的URL,Java HTTP getResponseCode返回200 [英] Java HTTP getResponseCode returns 200 for non-existent URL
问题描述
我原本期望此代码返回404,但它会产生输出:
I was expecting this code to return a 404, however it produces the output :
响应代码为200
是否有可能学习如何区分现有和不存在的网页。 。 。非常感谢,
Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,
try
{
// create the HttpURLConnection
URL url = new URL("http://www.thisurldoesnotexist");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + connection.getResponseCode());
}
推荐答案
编辑:我看到你了我打电话给 openConnection()
但不是 connect()
- 这可能是问题吗?我会期待 getResponseCode()
实际发出请求(如果还没有),但值得尝试...
I see you've call openConnection()
but not connect()
- could that be the problem? I would expect getResponseCode()
to actually make the request if it hasn't already, but it's worth just trying that...
这表明你可能有一些DNS解析器重定向到帮助者(垃圾邮件)页面,或类似的东西。
That suggests you've possible got some DNS resolver which redirects to a "helper" (spam) page, or something like that.
查看确切内容的最简单方法是使用 Wireshark - 拥有并捕获流量(仅限HTTP,使生活更轻松),然后运行您的代码。您应该能够看到正在发生的事情。
The easiest way to see exactly what's going on here is to use Wireshark - have that up and capturing traffic (HTTP-only, to make life easier) and then run your code. You should be able to see what's going on that way.
请注意,我不会期望404 - 因为这将涉及能够找到一个Web服务器谈谈开始。如果您尝试转到不涉及的主机,则不应该存在HTTP响应 。我希望 connect()
抛出异常。
Note that I wouldn't have expected a 404 - because that would involve being able to find a web server to talk to to start with. If you're trying to go to a host which doesn't involve, there shouldn't be an HTTP response at all. I'd expect connect()
to throw an exception.
这篇关于对于不存在的URL,Java HTTP getResponseCode返回200的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!