Java 检查 URL 是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4177864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a URL exists or not
提问by ha22109
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.
我需要检查一个 URL 是否存在。我想为此编写一个 servlet,即检查 URL 是否存在。如果输入的 URL 不存在,那么它应该返回一些消息。
回答by duffymo
You can make a connection, get the input stream back, and check for null.
您可以建立连接,取回输入流,并检查是否为空。
回答by Jigar Joshi
Better solution for HTTP :
更好的 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;
}
Source:http://www.rgagnon.com/javadetails/java-0059.html
来源:http://www.rgagnon.com/javadetails/java-0059.html
回答by aefxx
You could try HTTP's HEAD
method to see if the server returns a status code of 200
on a particular URL and act accordingly.
您可以尝试使用 HTTP 的HEAD
方法来查看服务器是否返回200
特定 URL 上的状态代码并采取相应措施。
See http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocoland scroll down to the Request Methods.
请参阅http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol并向下滚动到请求方法。
回答by ggerman
I used this bash script for check urls, but need put all files in a file "urls.csv"
我使用这个 bash 脚本来检查 url,但需要将所有文件放在一个文件“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 }'
}
url | \
while read CMD; do
echo $CMD
curl -Is $CMD | head -n 1
done