简体   繁体   English

确定URL是否存在?

[英]Determine if a URL exists or not?

I have a loop which iterates through a lot of URLs. 我有一个循环遍历许多URL的循环。 My problem is that the program is writing out the content of each url in the terminal, and I just want to ignore the broken urls. 我的问题是程序正在写终端中每个URL的内容,而我只想忽略损坏的URL。 How do I determine whether a URL is referring to something or not? 如何确定URL是否引用了某些内容?

Am I forced to make use of the exception FileNotFoundException that is being thrown? 我是否被迫使用抛出的异常FileNotFoundException? Because of that it affects other parts of the program too, I want to ensure that the main while loop directly jumps to the next iteration if the url is broken. 因此,它也会影响程序的其他部分,因此我想确保如果URL中断,则while循环会直接跳转到下一个迭代。 The exception is thrown by a method that I am using (within a class that I cannot change), how do I handle that? 我正在使用的方法(在无法更改的类中)抛出异常,我该如何处理?

Here is my loop (simplified): 这是我的循环(简化):

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.
}

So the openURL() is catching the FileNotFoundException and there is a lot of things printed in the terminal, I just want to ignore them, how do I do that? 因此,openURL()正在捕获FileNotFoundException,并且终端中印有很多内容,我只想忽略它们,该怎么办?

To verify if your String is valid URL or not, you can use Apache commons-validator URLValidator class as below: 要验证您的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");
}

Or even if you like to do it without using the Apache common-validator you can have something like below: 甚至即使您不使用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