简体   繁体   English

检查URL是否存在

[英]Checking if a URL exists or not

I need to check whether a URL exists or not. 我需要检查URL是否存在。 I want to write a servlet for this ie to check whether a URL exists or not. 我想为此编写一个servlet,即检查URL是否存在。 If the URL entered does not exist, then it should return some message. 如果输入的URL不存在,则应返回一些消息。

Better solution for HTTP : 更好的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 如果您正在寻找任何其他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;
  }

Source :http://www.rgagnon.com/javadetails/java-0059.html 资料来源 :http://www.rgagnon.com/javadetails/java-0059.html

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. 您可以尝试使用HTTP的HEAD方法来查看服务器是否在特定URL上返回状态代码200并采取相应措施。

See http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol and scroll down to the Request Methods . 请参阅http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol并向下滚动到“ 请求方法”

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

I used this bash script for check urls, but need put all files in a file "urls.csv" 我使用这个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM