Java HTTP getResponseCode 为不存在的 URL 返回 200 [英] Java HTTP getResponseCode returns 200 for non-existent URL

查看:39
本文介绍了Java HTTP getResponseCode 为不存在的 URL 返回 200的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原以为这段代码会返回 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 - 因为这涉及到能够找到一个网络服务器来开始对话.如果您尝试访问不涉及的主机,则根本不应该有 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.

这篇关于Java HTTP getResponseCode 为不存在的 URL 返回 200的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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