Programs that interact with the Internet might have the need to validate if a URL is valid. For instance, you might have a enter their URL on a comment made on your website or be accepting a feed from a third party application where you want to validate the URI to ensure proper formatting. This example will show how to check if a URL is valid URL using java regular expression, guava and apache commons.
Straight up Java
Using a java regular expression we will validate if a URL is valid.
@Test
public void validate_url_java () {
String urlRegex = "\b(https?|ftp|file|ldap)://"
+ "[-A-Za-z0-9+&@#/%?=~_|!:,.;]"
+ "*[-A-Za-z0-9+&@#/%=~_|]";
assertTrue("http://www.leveluplunch.com".matches(urlRegex));
}
Google Guava
Feature request 1191 URLValidator exists in guava's backlog.
@Ignore("not yet implemented")
@Test
public void validate_url_guava () {
}
Apache Commons
Based on php script Apache commons URL UrlValidator has a series of routines or behavior that is checks for to validate a URL.
@Test
public void validate_url_apache_commons () {
UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://www.leveluplunch.com"));
}