Thursday, October 20, 2011

Validate a URL in Java

To validate a URL String in Java we can use the java.net.URL object. First a URL object is created, passing the URL String to its constructor. If the URL String is malformed or invalid, a MalformedURLException will be thrown indicating a malformed URL. Next the URL is converted to a URI using the toURI() method. If URL is not formatted strictly according to to RFC2396 and cannot be converted to a URI, a URISyntaxException will be thrown indicating a malformed URL. The following code demonstrates how to validate a URL String.


package url;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

//
// The following example code demonstrates how to
// check if a given URL is valid or not.
//
public class CheckURLValidity {

    public static void main(String[] args) {

        String testURLString = "https://thermodynamiccomputing.com/main?&t=20&f=52";
        System.out.println(isValidURL(testURLString));

        testURLString = "http6://thermodynamiccomputing.com/";
        System.out.println(isValidURL(testURLString));

        testURLString = "http://thermodynamiccomputing.com/   dd";
        System.out.println(isValidURL(testURLString));

        testURLString = "http://<thermodynamiccomputing.com";
        System.out.println(isValidURL(testURLString));
    }

    private static boolean isValidURL(String pUrl) {

        URL u = null;
        try {
            u = new URL(pUrl);
        } catch (MalformedURLException e) {
            return false;
        }
        try {
            u.toURI();
        } catch (URISyntaxException e) {
            return false;
        }
        return true;
    }

}

Here is the output of the example code:
true
false
false
false
Piece of cake!!!

2 comments:

Unknown said...

Thanks for the post. It helped me a lot

Anonymous said...

Thanks for such a good post.. :)