How to check for a valid URL in Java?
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.
Here is way I tried and found useful,
URL u = new URL(name); // this would check for the protocol
u.toURI(); // does the extra checking required for validation of URI
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:
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
private static final String URL_PATTERN =
"/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
// 12 3 4 5 6 7 8 9
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
*/
private static final int PARSE_URL_SCHEME = 2;
/**
* Includes hostname/ip and port number.
*/
private static final int PARSE_URL_AUTHORITY = 4;
private static final int PARSE_URL_PATH = 5;
private static final int PARSE_URL_QUERY = 7;
private static final int PARSE_URL_FRAGMENT = 9;
You can easily build your own validator from there.
My favorite approach, without external libraries:
try {
URI uri = new URI(name);
// perform checks for scheme, authority, host, etc., based on your requirements
if ("mailto".equals(uri.getScheme()) {/*Code*/}
if (uri.getHost() == null) {/*Code*/}
} catch (URISyntaxException e) {
}