我使用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