我正在使用 HttpURLConnection
来验证来自数据库的 URL。有时,对于某些 URL,我会遇到异常,我假设它们超时,但实际上可以访问(没有 400 范围错误)。
增加超时似乎并不重要,我仍然遇到异常。我可以在 catch 区域进行第二次检查来验证 URL 是否确实错误?相关代码如下。它适用于 99.9% 的 URL,也就是 0.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;
}
最佳答案
取决于您要检查的内容。但我猜 Validating URL in Java 为您提供帮助。
你有两种可能性:
检查语法(“此网址是真实网址还是虚构的?”)
有大量的文字描述了如何做到这一点。基本上搜索 RFC 3986。我猜有人已经实现了这样的检查。
检查语义(“URL 可用吗?”)
尽管有不同的工具可用于在 java 中发送 http 请求,但实际上并没有更快的方法。您可以发送 HEAD 请求而不是 GET,因为 HEAD 省略 HTTP 正文,并且可能会导致更快的请求和更少的超时。
关于java - 寻找在 Java 中验证 URL 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41167256/