开发者

How to Optimally check for URL validity

开发者 https://www.devze.com 2023-04-13 07:12 出处:网络
A straightforward way to check for URL validity, is to simply handle a MalformedURLException exception:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号