//2012-04-06 johnpfeiffer
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class CheckURL
{
public static final int CONNECTIONTIMEOUT = 5000;
public static final int READTIMEOUT = 5000;
CheckURL()
{
}
boolean isValid( String input )
{
HttpURLConnection urlConnection = null;
boolean result = false;
try
{
URL url = new URL( input );
urlConnection = (HttpURLConnection) url.openConnection();
//HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod( "HEAD" );
urlConnection.setConnectTimeout( CONNECTIONTIMEOUT ); /* timeout after 5s if can't connect */
urlConnection.setReadTimeout( READTIMEOUT ); /* timeout after 5s if the page is too slow */
urlConnection.connect();
String location = urlConnection.getHeaderField( "Location" );
if( location != null && !location.equals( input ) )
{
System.out.println( "INFO:Redirect:" + location );
result = false;
}else
{
if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK )
{ result = true;
}
}
}catch( MalformedURLException me )
{ System.err.print( "ERROR:MalformedURL " );
}catch( Exception e )
{ // e.printStackTrace();
}finally
{ if (urlConnection != null)
{ urlConnection.disconnect();
}
}
return result;
}
public static String usage()
{ return "Usage (5 second timeout by default): java -jar CheckURL http://domain.com";
}
public static void main( String[] args )
{
CheckURL c = new CheckURL();
if( args.length == 1 )
{ System.out.println( c.isValid( args[0] ) );
}else
{ System.out.println( usage() );
System.out.println( "https://google.com = " + c.isValid( "https://google.com" ) );
System.out.println( "http://testabcd1234testabcd.com = " + c.isValid( "http://testabcd1234testabcd.com" ) );
System.out.print( "htp:/testabcd1234testabcdcom " + c.isValid( "htp:/testabcd1234testabcdcom" ) );
}
}
} //end class