Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for a valid URL in Java?

What is the best way to check if a URL is valid in Java?

If tried to call new URL(urlString) and catch a MalformedURLException, but it seems to be happy with anything that begins with http://.

I'm not concerned about establishing a connection, just validity. Is there a method for this? An annotation in Hibernate Validator? Should I use a regex?

Edit: Some examples of accepted URLs are http://*** and http://my favorite site!.

like image 836
Eric Wilson Avatar asked Feb 09 '10 16:02

Eric Wilson


1 Answers

Consider using the Apache Commons UrlValidator class

UrlValidator urlValidator = new UrlValidator(); urlValidator.isValid("http://my favorite site!"); 

There are several properties that you can set to control how this class behaves, by default http, https, and ftp are accepted.

like image 119
Tendayi Mawushe Avatar answered Sep 20 '22 19:09

Tendayi Mawushe