Search code examples
javaurlconnection

How to make sure URLConnection is valid and will successfully connect in Java?


how can you ensure URL you receive from users is a valid url and not just a http://nothing.com

my code looks like this:

String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com
URL url = new URL(urlFromUser);

// this might fail
URLConnection urlConnection = url.openConnection();

and try catch is not enough, i want to make sure the site is real


Solution

  • you can also use:

    if(new InetSocketAddress(urlFromUser, 80).isUnresolved()) {
        // URL is a not a valid server address
    }
    else {
        // URL is valid
    }