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.
For HTTP you should check for the HTTP status code 404 .
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"); } ?>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With