How to validate URL in Java?
You can use org.apache.commons.validator.routines.UrlValidator class (ver 1.4) or apache.commons.validator.UrlValidator class to validate a given URL. The new UrlValidator is in the routines package and the apache.commons.validator.UrlValidator class will be removed in a future release. Here is an example,
...
public class ValidateUrlExample{
public static void main(String[] args) {
System.out.println("*** doUserSpecifiedSchemes ***");
doUserSpecifiedSchemes();
System.out.println("\n*** doDefaultSchemes ***");
doDefaultSchemes();
}
public static void doUserSpecifiedSchemes() {
String[] schemes = {"http","https"};
UrlValidator urlValidator = new UrlValidator(schemes);
String url = "http://foo.bar.com/";
if (urlValidator.isValid(url)) {
System.out.println(url + " is valid");
}
else {
System.out.println(url + " is invalid");
}
url = "ftp://foo.bar.com/";
if (urlValidator.isValid(url)) {
System.out.println(url + " is valid");
}
else {
System.out.println(url + " is invalid");
}
}
public static void doDefaultSchemes() {
UrlValidator urlValidator = new UrlValidator();
String url = "http://foo.bar.com/";
if (urlValidator.isValid(url)) {
System.out.println(url + " is valid");
}
else {
System.out.println(url + " is invalid");
}
url = "ftp://foo.bar.com/";
if (urlValidator.isValid(url)) {
System.out.println(url + " is valid");
}
else {
System.out.println(url + " is invalid");
}
}
}
output:
*** doUserSpecifiedSchemes ***
http://foo.bar.com/ is valid
ftp://foo.bar.com/ is invalid
*** doDefaultSchemes ***
http://foo.bar.com/ is valid
ftp://foo.bar.com/ is valid
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?