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
There are several properties that you can set to control how this class behaves, by default
http
,https
, andftp
are accepted.Judging by the source code for
URI
, theconstructor does more validation than the other constructors. You might try that one, but YMMV.
validator package:
There seems to be a nice package by Yonatan Matalon called UrlUtil. Quoting its API:
Sun's approach - check the network address
Sun's Java site offers connect attempt as a solution for validating URLs.
Other regex code snippets:
There are regex validation attempts at Oracle's site and weberdev.com.
I didn't like any of the implementations (because they use a Regex which is an expensive operation, or a library which is an overkill if you only need one method), so I ended up using the java.net.URI class with some extra checks, and limiting the protocols to: http, https, file, ftp, mailto, news, urn.
And yes, catching exceptions can be an expensive operation, but probably not as bad as Regular Expressions:
Here is way I tried and found useful,
I'd love to post this as a comment to Tendayi Mawushe's answer, but I'm afraid there is not enough space ;)
This is the relevant part from the Apache Commons UrlValidator source:
You can easily build your own validator from there.