检查URL是否存在
您可以建立连接,获取输入流并检查是否为空。对于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;
}
}
如果你正在寻找任何其他URL试试这个代码
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
'http'不是URL中唯一的协议/方案。 – 2010-11-14 15:00:58
@Michael Konietzka更新可能会回答您的评论 – 2010-11-14 16:05:33
我需要使用Httpclient及其方法来检查url的存在 可以请你告诉如何使用httpClient服务。我试图在一个servelt中编写此服务,但它是给予例外。 – ha22109 2010-11-14 16:46:33
您可以尝试使用HTTP的HEAD
方法来查看服务器是否返回了状态代码200
特定的URL并据此采取行动。
请参阅http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol并向下滚动到请求方法。
我用于检查的URL这个bash脚本,但需要把所有文件放在一个文件“urls.csv”
#!/bin/bash
###############################################
# mailto: [email protected]
# checkurls
# https://github.com/ggerman/checkurls/
# require curl
###############################################
url() {
cat urls.csv |
replace |
show
}
replace() {
tr ',' ' '
}
show() {
awk '{print $1}'
}
url | \
while read CMD; do
echo $CMD
curl -Is $CMD | head -n 1
done
一个URL不能一概说是不存在的。 – SLaks 2010-11-14 14:14:24
为什么java文档? – 2010-11-14 15:51:21