tags:

views:

141

answers:

3

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
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
It actually performs other checks too, e.g. port numbers.
Grodriguez
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
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
+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
+1 for being different :)
willcodejavaforfood
no need to duplicate others' answers ;)
Bozho
+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
-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
@Stephen..thanks for pointing out..just picked that one from my bookmarks. Removed the incorrect link now.
johnbk