The java.net.URL class is actually not a good way to validate URLs. MalformedURLException not imposed on all invalid URLs at build time. The IOException trap on java.net.URL#openConnection().connect() does not check the URL, just let it know or not, the connection can be established.
Consider this piece of code:
try { new URL("http://.com"); new URL("http://com."); new URL("http:// "); new URL("ftp://::::@example.com"); } catch (MalformedURLException malformedURLException) { malformedURLException.printStackTrace(); }
.. which does not throw any exceptions.
I recommend using some validation API implemented using context free grammar, or just use regular expressions in a very simplified validation. However, I need someone to offer an excellent or standard API for this, I just recently started looking for it myself.
Note It has been suggested that the URL#toURI() is combined with java.net. URISyntaxException exception handling java.net. URISyntaxException java.net. URISyntaxException may facilitate URL checking. However, this method only catches one of the simplest cases above.
The conclusion is that there is no standard java URL parser for checking URLs.
Martin May 11 '11 at 14:18 2011-05-11 14:18
source share