How to check a valid url in Java?

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

If you tried to call new URL(urlString) and catch a MalformedURLException , but he seems pleased with what starts with http:// .

I'm not interested in making a connection, just reality. Is there any way to do this? Annotations in Hibernate Validator? Should I use regex?

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

+81
java url validation
Feb 09 '10 at 16:29
source share
8 answers

Using Apache Commons UrlValidator class

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

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

+90
Feb 09 '10 at 16:44
source share

This is how 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 
+53
Apr 19 '11 at 16:03
source share

I would like to post this as a comment on Tendaya Maushu's answer , but I'm afraid there is not enough space;)

This is an important 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 create your own validator.

+6
Dec 19 '12 at 18:26
source share

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) { } 
+4
Nov 18 '13 at 2:33
source share

check package:

It seems like a good package by Yonatan Matalon called UrlUtil . Indication of its API:

 isValidWebPageAddress(java.lang.String address, boolean validateSyntax, boolean validateExistance) Checks if the given address is a valid web page address. 

Sun Approach - Check Network Address

The Sun Java site suggests connecting try as a solution for checking URLs.

Other regular expression code snippets:

There are attempts to validate regular expressions on Oracle and weberdev.com .

+3
Feb 09 '10 at 16:39
source share

Judging by the source code for the URI ,

 public URL(URL context, String spec, URLStreamHandler handler) 
Constructor

makes a bigger check than other constructors. You can try this, but YMMV.

+3
Feb 09 2018-10-09
source share

The most reliable way is to check for URLs:

 public boolean isURL(String url) { try { (new java.net.URL(url)).openStream().close(); return true; } catch (Exception ex) { } return false; } 
+3
Feb 07 '19 at 9:42
source share

I didn’t like any of the implementations (because they use Regex, which is an expensive operation, or a library that is redundant if you only need one method), so I ended up using the java.net.URI class with some additional checks and a restriction Protocols: http, https, file, ftp, mailto, news, urn.

And yes, catching an exception can be an expensive operation, but probably not as bad as regular expressions:

 final static Set<String> protocols, protocolsWithHost; static { protocolsWithHost = new HashSet<String>( Arrays.asList( new String[]{ "file", "ftp", "http", "https" } ) ); protocols = new HashSet<String>( Arrays.asList( new String[]{ "mailto", "news", "urn" } ) ); protocols.addAll(protocolsWithHost); } public static boolean isURI(String str) { int colon = str.indexOf(':'); if (colon < 3) return false; String proto = str.substring(0, colon).toLowerCase(); if (!protocols.contains(proto)) return false; try { URI uri = new URI(str); if (protocolsWithHost.contains(proto)) { if (uri.getHost() == null) return false; String path = uri.getPath(); if (path != null) { for (int i=path.length()-1; i >= 0; i--) { if ("?<>:*|\"".indexOf( path.charAt(i) ) > -1) return false; } } } return true; } catch ( Exception ex ) {} return false; } 
+2
Jun 25 '13 at 9:12
source share



All Articles