[英]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.