How can i check, if a string is an url in java?
+9
A:
You can try to create a java.net.URL
object out of it. If it is not a proper URL, a MalformedURLException
will be thrown.
Grodriguez
2010-10-14 09:13:26
Just to be clear, it would only throw a MalformedURLException `if no protocol is specified, or an unknown protocol is found`. Unlike, Apache's UrlValidator, no additional validation is performed.
dogbane
2010-10-14 10:44:29
It actually performs other checks too, e.g. port numbers.
Grodriguez
2010-10-14 10:53:19
I quoted that from the javadocs http://download.oracle.com/javase/6/docs/api/java/net/URL.html. They don't state any other checks.
dogbane
2010-10-14 11:05:52
That's what the Javadocs say, however the checks are performed (you can try it yourself, or have a look at the source code if you wish)
Grodriguez
2010-10-14 11:12:51
+11
A:
You can use UrlValidator
from commons-validator. It will save you from writing code where the logic flow is guided by caching an exception, which is generally considered a bad practice. In this case, however, I think it's fine to do as others suggested, if you move this functionality to an utility method called isValidUrl(..)
Bozho
2010-10-14 09:16:41
+1
A:
I agree with other answers...but I think we can also use a regex for URL to see if the string matches the url pattern.
johnbk
2010-10-14 09:23:10
-1 - The linked regex is incorrect. There are valid URLs that it won't match: the general syntax is `<scheme>:<scheme-specific-part>` for arbitrary schemes, but the regex only matches specific schemes. OTOH, the regex does not capture %xx escaping rules, so it will match invalid URLs.
Stephen C
2010-10-14 10:10:24
@Stephen..thanks for pointing out..just picked that one from my bookmarks. Removed the incorrect link now.
johnbk
2010-10-14 10:19:03