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!.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With