This post covers various methods to validate a 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.

Download Code

Output:

The URL https://techiedelight.com/ 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 UrlValidator parsing rules by specifying any of the following 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.

The following program demonstrates it:

2. Using Regular Expression provided by OWASP

We can also use OWASP Validation Regex, which is considered to be very safe. We can use the following regular expression to check for a valid URL.

^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$

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

Validator.URL=^(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\:\\'\\/\\\\\\+=&%\\$#_]*)?$

Download  Run Code

Output:

The URL https://techiedelight.com/ is valid

3. Using java.net.URL

We can also java.net.URL 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 the toURI() method that throws a URISyntaxException if the URL is not formatted strictly according to RFC 2396 and cannot be converted to a URI.

Download  Run Code

Output:

The URL https://techiedelight.com/ is valid

That’s all about validating a URL in Java.

 
Also See:

Validate an IP address in Java