How to Optimally check for URL validity
A straightforward way to check for URL validity, is to simply handle a MalformedURLException
exception:
try {
URL base = new URL(SomeString);
}
cat开发者_高级运维ch (MalformedURLException e) {
e.printStackTrace();
// handles this in some way
}
But AFAIK, using exceptions to implement program logic is conceptually incorrect (and perhaps more costly in runtime performance).
On the other hand, I don't know of a Java method that does isValid(String url)
.
Is there a better way to check URL's string validity without instantiating a URL object (and handling a MalformedURLException
)?
Yes, write a regular expression to check it.
Regular expression to match URLs in Java
You can move that functionality to an utility method: URLUtils.isValid(url)
where you return false
from catch
. After that you can switch to another method, if you decide to.
For example you can use UrlValidator
from commons-validator.
精彩评论