How to verify if a String in Java is a valid URL

If you program in Android, you could use android.webkit.URLUtil to test.

URLUtil.isHttpUrl(url)
URLUtil.isHttpsUrl(url)

Hope it would be helpful.


For Android just add this line:

boolean isValid = URLUtil.isValidUrl( "your.uri" );

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.


You can use UrlValidator from commons-validator. It will save you from writing code where the logic flow is guided by catching 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(..)

Tags:

Java

Url