我需要檢查一組Intranet站點。我試圖使用下面的代碼。 (剛剛通過在互聯網上隨機搜索獲得此代碼)。我在我的行動課上調用了這個方法。但是進入例外部分的大多數網站。即使我能夠從我的瀏覽器打開這些網站,我也獲得了協議例外和UnknownHostException
。Java Struts - Dead Link Checker
代碼以供參考:
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();
}
}
}