[英]Checking if a URL exists or not
我需要檢查URL是否存在。 我想為此編寫一個servlet,即檢查URL是否存在。 如果輸入的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的HEAD
方法來查看服務器是否在特定URL上返回狀態代碼200
並采取相應措施。
請參閱http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol並向下滾動到“ 請求方法” 。
您可以建立連接,獲取輸入流,並檢查是否為null。
我使用這個bash腳本來檢查URL,但是需要將所有文件放在文件“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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.