我使用HttpURLConnection
來驗證來自數據庫的URL。有時候,在某些網址我會得到一個異常,我認爲他們超時但實際上可以達到(沒有400範圍錯誤)。正在尋找一種替代方法來驗證Java中的URL
增加超時似乎並不重要,我仍然得到一個異常。在捕獲區域中是否有第二次檢查來驗證URL是否有誤?相關代碼如下。它適用於99.9%的網址,即.01%。
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");
connection.connect() ;
int responseCode = connection.getResponseCode();
if (responseCode >= 401)
{
String prcMessage = "ERROR: URL " + url + " not found, response code was " + responseCode + "\r";
System.out.println(prcMessage);
VerifyUrl.writeToFile(prcMessage);
return (false);
}
}
catch (IOException exception)
{
String errorMessage = ("ERROR: URL " + url + " did not load in the given time of " + timeout + " milliseconds.");
System.out.println(errorMessage);
VerifyUrl.writeToFile(errorMessage);
return false;
}
你可以使用正則表達式。 https://docs.oracle.com/javase/tutorial/essential/regex/ – aleb2000
你可以使用Apache公共UrlValidator。 https://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/UrlValidator.html – ntalbs