Validate an URL in Java

This post covers various methods to validate an url in Java.


1. Using Apache Commons Validator

Apache Commons Validator package contains several standard validation routines. We can use UrlValidator class that provides URL validation by checking the scheme, authority, path, query, and fragment.




The URL is valid


We can also specify the valid schemes to be used in validating in addition to or instead of the default values (HTTP, HTTPS, FTP).


We can also change the parsing rules of the UrlValidator by specifying any of below instructions to the Validator.

  1. ALLOW_2_SLASHES option allow two slashes in the path component of the URL.
  2. ALLOW_ALL_SCHEMES option allows all validly formatted schemes to pass validation instead of supplying a set of valid schemes.
  3. ALLOW_LOCAL_URLS option allow local URLs, such as http://localhost/.
  4. NO_FRAGMENTS option disallows any URL fragments.



2. Using Regular Expression provided by OWASP

We can also use OWASP Validation Regex which are considered to be very safe. Below regular expression can be used to check for a valid url.


ESAPI validation routine can also be used which uses the following regular expression.



Download   Run Code


The URL is valid


3. Using

We can also class to validate a URL. The idea is to create a URL object from the specified String representation. A MalformedURLException will be thrown if no protocol is specified, or an unknown protocol is found, or spec is null. Then we call toURI() method that throws a URISyntaxException if the URL is not formatted strictly according to to RFC 2396 and cannot be converted to a URI.


Download   Run Code


The URL is valid

Also See: Validate an IP address in Java

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of