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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
}
Source :http://www.rgagnon.com/javadetails/java-0059.html
回答2:
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.
See http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol and scroll down to the Request Methods.
回答3:
You can make a connection, get the input stream back, and check for null.
回答4:
I used this bash script for check urls, but need put all files in a file "urls.csv"
#!/bin/bash
###############################################
# mailto: ggerman@gmail.com
# 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