public static boolean isValidUrl ( String url ) { HttpURLConnection huc = null ; boolean isValid = false ; try { URL u = new URL ( url ) ; huc = ( HttpURLConnection ) u . openConnection ( ) ; huc . setRequestMethod ( "GET" ) ; huc . connect ( ) ; int response = huc . getResponseCode ( ) ; if ( response != HttpURLConnection . HTTP_OK ) { throw new IOException ( String . format ( "URL %s did not return a valid response code while attempting to connect. Expected: %d. Received: %d" , url , HttpURLConnection . HTTP_OK , response ) ) ; } isValid = true ; } catch ( IOException e ) { logger . warn ( "A problem happened while trying to verify url: {} Error Message: {}" , url , e . getMessage ( ) ) ; } finally { if ( huc != null ) { huc . disconnect ( ) ; } ; } return isValid ; }
Tests if a string is a valid URL Will open a connection and make sure that it can connect to the URL it looks for an HTTP status code of 200 on a GET . This is a valid URL .