Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a URL exists or not

Tags:

java

url

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.

like image 835
ha22109 Avatar asked Nov 14 '10 14:11

ha22109


People also ask

Which HTTP method check if URI exists?

For HTTP you should check for the HTTP status code 404 .

How validate URL in PHP?

php $url = "http://www.qbaki.com"; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Validate url if (filter_var($url, FILTER_VALIDATE_URL) !== false) { echo("$url is a valid URL"); } else { echo("$url is not a valid URL"); } ?>


1 Answers

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

like image 158
jmj Avatar answered Oct 12 '22 22:10

jmj