How to verify if a String in Java is a valid URL
Solution 1:
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.
Solution 2:
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(..)
Solution 3:
For Android just add this line:
boolean isValid = URLUtil.isValidUrl( "your.uri" );
Solution 4:
If you program in Android, you could use android.webkit.URLUtil
to test.
URLUtil.isHttpUrl(url)
URLUtil.isHttpsUrl(url)
Hope it would be helpful.