5

I'm trying to make a is-website-down utility with java, but I have some problems.

Is there a way to check if a website exists? I tried this to see if a website is down:

URL url = new URL("http://localhost");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
int code = httpConnection.getResponseCode();
System.out.println("code: " + code);

It goes through IOException for Connection refused: connect when i.e. i try to connect to localhost while there is no active http server listening (the site is down).

I thought it would happen the same thing with some site that actually doesn't exist i.e.

URL url = new URL("http://www.sdfasfjkhaslfjkhaslkdjfhasldkjf.it");

But i receive a HTTP Status code 200 because my ISP automatically redirects me to a random advertisement page if the site i'm searching for doesn't exist.

So, if a site is down, my program says "Well, your website is down", but if the site doesn't exist my program says "Oh, your website is up and running!", and that's not really good.

Is there a way to check if a website exists?

4

3 回答 3

1

阅读您对 ISP DNS 中毒的评论。您的 ISP 正在向您提供/租用他们控制的 DNS 服务器,该服务器会捕获所有NXDOMAIN响应并将中毒结果返回到他们控制的服务器。

在您进行 HTTP 检查之前,我会使用Google 公共 DNS或其他一些公开的有效 DNS 服务器对 A 记录进行DNS 检查。NXDOMAIN当域无效时,Google 公共 DNS 会返回。在 Java 中,您可能需要使用dnsjava之类的东西来直接访问所需的 DNS 记录。

最后,进行两次检查,一次检查针对已知良好来源的有效 DNS 记录,然后检查 HTTP 是否存在。

于 2013-04-24T20:46:48.893 回答
1

刚刚发现Java - 如何找到一个 url 的重定向 url?这建议设置 httpConnection.setFollowRedirects(false) - 如果他们正在执行实际重定向,这可能会有所帮助。如果他们没有重定向,而只是提供自己的内容,则不确定除了检测内容是否符合您的预期或是否是广告之外还有很多工作要做。

于 2013-04-24T20:52:19.667 回答
0

您可能要添加:

HttpURLConnection.setFollowRedirects(false);
// note : or
//        httpConnection.setInstanceFollowRedirects(false);

和控制:

(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
于 2013-09-15T17:28:08.873 回答