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.

 

Download

Output:

The URL http://www.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 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.

^((((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 http://www.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 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

Output:

The URL http://www.techiedelight.com/ is valid

 
Also See: Validate an IP address in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz