检查URL是否存在

时间:2010-11-14 14:12:47

标签: java url

我需要检查网址是否存在。我想为此编写一个servlet,即检查URL是否存在。如果输入的URL不存在,则应返回一些消息。

4 个答案:

答案 0 :(得分:25)

更好的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;
    }
  }  

如果您正在寻找任何其他网址,请尝试使用此代码

  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

答案 1 :(得分:1)

您可以尝试使用HTTP的HEAD方法查看服务器是否在特定网址上返回200的状态代码并采取相应措施。

请参阅http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol并向下滚动到请求方法

答案 2 :(得分:0)

您可以建立连接,获取输入流,并检查是否为空。

答案 3 :(得分:-2)

我将这个bash脚本用于检查网址,但需要将所有文件放在一个文件“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
相关问题