Checking for errors when connecting to a URL

You can use the response codes that are provided in the HttpURLConnection class. The idea is send the HEAD request instead of the (default) GET command and read out the error code (HTTP_OK = generally ok URL).

The following example shows how this is realized. When run as an application, it will also follow redirects (setFollowRedirects(true)). An applet is not allowed
to change this variable.

import java.net.*;
import java.io.*;
 
public class Main
{
   public static void main(String args[]) 
   {
      try {
         if (args.length != 1) {
            System.err.println("Usage: java Main <URL>");
            System.exit(0);
         }
 
         HttpURLConnection.setFollowRedirects(true);
         HttpURLConnection con = (HttpURLConnection) new URL(args[0]).openConnection();
         con.setRequestMethod("HEAD");
         if (con.getResponseCode() == HttpURLConnection.HTTP_OK)
            System.out.println(args[0] + " is valid");
         else
            System.out.println("Error with " + args[0] + ", code is " + con.getResponseCode()); 
      }
      catch(MalformedURLException e) { System.out.println(e); }
      catch(ProtocolException e) { System.out.println(e); }
      catch(IOException e) { System.out.println(e); }
   }
}
java Main http://www.esus.com               
java Main http://www.esus.com/drdre.html 

returns:

http://www.esus.com is valid
Error with http://www.esus.com/drdre, code is 404