2010-11-14 164 views
7

我需要檢查URL是否存在。我想爲此編寫一個servlet,即檢查URL是否存在。如果輸入的URL不存在,那麼它應該返回一些消息。檢查URL是否存在

+6

一個URL不能一概說是不存在的。 – SLaks 2010-11-14 14:14:24

+0

爲什麼java文檔? – 2010-11-14 15:51:21

回答

0

您可以建立連接,獲取輸入流並檢查是否爲空。對於HTTP

22

更好的解決方案:

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

+2

'http'不是URL中唯一的協議/方案。 – 2010-11-14 15:00:58

+0

@Michael Konietzka更新可能會回答您的評論 – 2010-11-14 16:05:33

+0

我需要使用Httpclient及其方法來檢查url的存在 可以請你告訴如何使用httpClient服務。我試圖在一個servelt中編寫此服務,但它是給予例外。 – ha22109 2010-11-14 16:46:33

0

我用於檢查的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