繁体   English   中英

确定URL是否存在?

[英]Determine if a URL exists or not?

我有一个循环遍历许多URL的循环。 我的问题是程序正在写终端中每个URL的内容,而我只想忽略损坏的URL。 如何确定URL是否引用了某些内容?

我是否被迫使用抛出的异常FileNotFoundException? 因此,它也会影响程序的其他部分,因此我想确保如果URL中断,则while循环会直接跳转到下一个迭代。 我正在使用的方法(在无法更改的类中)抛出异常,我该如何处理?

这是我的循环(简化):

while(!queue.isEmpty()) {
    URL thisURL = (URL)queue.poll();
    String page = Customurlclass.openURL(thisURL); // return a string containing the page that the url is refering to.
    System.out.println(page);
    // Some other things is also happening here, an I don't want them to happen if the url is broken.
}

因此,openURL()正在捕获FileNotFoundException,并且终端中印有很多内容,我只想忽略它们,该怎么办?

要验证您的String是否是有效的URL,可以使用Apache commons-validator URLValidator类 ,如下所示:

String[] schemes = {"http","https"}; // DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("ftp://foo.bar.com/")) {
   System.out.println("url is valid");
} else {
   System.out.println("url is invalid");
}

甚至即使您不使用Apache common-validator也可以这样做,也可以像下面这样:

try {
    URL url = new URL("http://www.yoursite.com/");
    URLConnection conn = url.openConnection();
    conn.connect();
} catch (MalformedURLException e) {
    // the URL is not in a valid form
} catch (IOException e) {
    // the connection couldn't be established
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM