Java Struts - 死链接检查器
我需要检查一组 Intranet 站点。我尝试使用下面的代码。 (刚刚通过在互联网上随机搜索获得此代码)。我在我的动作类上调用了这个方法。但大多数网站都会进入例外部分。尽管我能够从浏览器打开这些网站,但我还是收到了协议异常和 UnknownHostException
。
参考代码:
public boolean isLive(String link) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(link);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("HEAD");
urlConnection.setConnectTimeout(5000); /* timeout after 5s if can't connect */
urlConnection.setReadTimeout(5000); /* timeout after 5s if the page is too slow */
urlConnection.connect();
String redirectLink = urlConnection.getHeaderField("Location");
if (redirectLink != null && !link.equals(redirectLink)) {
return isLive(redirectLink);
} else {
return urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK;
}
} catch (Exception e) {
return false;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
I need to check a set intranet sites. I tried to use the below code. (Just got this code by random search on the internet). I called this method on my action class. But most of the sites where going into the exception part. I was getting Protocol exceptions and UnknownHostException
even though I was able to open these sites from my browser.
Code for reference:
public boolean isLive(String link) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(link);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("HEAD");
urlConnection.setConnectTimeout(5000); /* timeout after 5s if can't connect */
urlConnection.setReadTimeout(5000); /* timeout after 5s if the page is too slow */
urlConnection.connect();
String redirectLink = urlConnection.getHeaderField("Location");
if (redirectLink != null && !link.equals(redirectLink)) {
return isLive(redirectLink);
} else {
return urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK;
}
} catch (Exception e) {
return false;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为代码没有问题。
您的连接超时为 5 秒
任何花费超过 5 秒的查询都将被视为死链接。您的浏览器的超时时间比您的代码长得多,因此您可以在浏览器中浏览这些网站
I think No Problem with the code.
You have a connection timeout of 5 seconds
Any query that takes more than 5 seconds will be considered a dead link.Your Browser have much longer timeout than your code so you are able to browse those sites in the browser
如果您遇到协议异常和未知主机异常,我们需要了解更多信息才能提供帮助。您的机器是否配置为通过代理?您是否有不会被应用程序容器的用户共享的主机定义?
另外,考虑使用类似 HttpClient 的东西来包装这样的东西,而不是手动执行;只是太多的工作。
If you're getting protocol exceptions and unknown host exceptions we'd need to know more in order to help. Is your machine configured to go through a proxy? Do you have host definitions that wouldn't be shared by your app container's user?
Also, consider using something like HttpClient to wrap up stuff like this rather than doing it manually; just too much work.