Regex Rookie
Regex Rookie

Reputation: 10662

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);
}
catch (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)?

Upvotes: 4

Views: 1700

Answers (2)

Bozho
Bozho

Reputation: 597422

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.

Upvotes: 2

smp7d
smp7d

Reputation: 5032

Yes, write a regular expression to check it.

Regular expression to match URLs in Java

Upvotes: 3

Related Questions