Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

java - Checking if a URL exists or not

I need to check whether a URL exists or not. I want to write a servlet for this i.e. to check whether a URL exists or not. If the URL entered does not exist, then it should return some message.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Better solution for 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

  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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...