检查URL是否存在 [英] Checking if a URL exists or not
本文介绍了检查URL是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检查网址是否存在。我想为此编写一个servlet,即检查URL是否存在。如果输入的URL不存在,那么它应该返回一些消息。
I need to check whether a URL exists or not. I want to write a servlet for this i.e. to check whether a URL exists or not. If the URL entered does not exist, then it should return some message.
推荐答案
更好的HTTP解决方案:
Better solution for HTTP :
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
如果您正在寻找任何其他网址,请尝试使用此代码
If you are looking for any other URL try this code
public static boolean exists(String URLName){
boolean result = false;
try {
url = new URL("ftp://ftp1.freebsd.org/pub/FreeBSD/");
//url = new URL("ftp://ftp1.freebsd.org/pub/FreeBSD123/");//this will fail
input = url.openStream();
System.out.println("SUCCESS");
result = true;
} catch (Exception ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
来源:http://www.rgagnon .com / javadetails / java-0059.html
Source :http://www.rgagnon.com/javadetails/java-0059.html
这篇关于检查URL是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文