2010-11-14 165 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