Validate a URL in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import org.apache.commons.validator.routines.UrlValidator; // Java program to validate a URL in Java class Main { public static boolean urlValidator(String url) { // Get an `UrlValidator` using default schemes UrlValidator defaultValidator = new UrlValidator(); return defaultValidator.isValid(url); } public static void main(String[] args) { String url = "https://techiedelight.com/"; // Validate an URL if (urlValidator(url)) { System.out.print("The url " + url + " is valid"); } else { System.out.print("The url " + url + " isn't valid"); } } } |
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).
|
1 2 3 4 5 6 7 8 |
public static boolean urlValidator(String url) { // Get an `UrlValidator` with custom schemes String[] customSchemes = { "sftp", "scp", "https" }; UrlValidator customValidator = new UrlValidator(customSchemes); return customValidator.isValid(url); } |
We can also change the UrlValidator parsing rules by specifying any of the following instructions to the Validator.
ALLOW_2_SLASHESoption allow two slashes in the path component of the URL.ALLOW_ALL_SCHEMESoption allows all validly formatted schemes to pass validation instead of supplying a set of valid schemes.ALLOW_LOCAL_URLSoption allow local URLs, such as http://localhost/.NO_FRAGMENTSoption disallows any URL fragments.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 |
public static boolean urlValidator(String url) { // Get an `UrlValidator` that allows double slashes in the path UrlValidator doubleSlashValidator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); return doubleSlashValidator.isValid(url); } |
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\\-\\.\\?\\,\\:\\'\\/\\\\\\+=&%\\$#_]*)?$
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.regex.Matcher; import java.util.regex.Pattern; // Java program to validate a URL in Java class Main { private static final String URL_REGEX = "^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))" + "(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)" + "([).!';/?:,][[:blank:]])?$"; private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX); public static boolean urlValidator(String url) { if (url == null) { return false; } Matcher matcher = URL_PATTERN.matcher(url); return matcher.matches(); } public static void main(String[] args) { String url = "https://techiedelight.com/"; // Validate an URL if (urlValidator(url)) { System.out.print("The URL " + url + " is valid"); } else { System.out.print("The URL " + url + " isn't valid"); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; // Java program to validate a URL in Java class Main { public static boolean urlValidator(String url) { try { new URL(url).toURI(); return true; } catch (URISyntaxException exception) { return false; } catch (MalformedURLException exception) { return false; } } public static void main(String[] args) { String url = "https://techiedelight.com/"; // Validate an URL if (urlValidator(url)) { System.out.print("The URL " + url + " is valid"); } else { System.out.print("The URL " + url + " isn't valid"); } } } |
Output:
The URL https://techiedelight.com/ is valid
That’s all about validating a URL in Java.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)