2

I want to check the validity of a URL address, so after some research, i find that using apache.commons.validator.UrlValidator class is a good solution to do that, this is an example of code :

 import org.apache.commons.validator.UrlValidator; public class ValidateUrlExample{ public static void main(String[] args) { UrlValidator urlValidator = new UrlValidator(); //valid URL if (urlValidator.isValid("http://www.mkyong.com")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); } //invalid URL if (urlValidator.isValid("http://invalidURL^$&%$&^")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); } } } 

but android doesn't recognize the class "org.apache.commons.validator" Does anyone know what should I do to fix that ?

Thanks in advance

3
  • FYI If you use new URL("putyoururlhere") with a invalid url, it throws a MalformedURLException - maybe you can use it. More info at developer.android.com/reference/java/net/… Commented Feb 8, 2012 at 17:20
  • I will take your solution into consideration, Thank you Commented Feb 8, 2012 at 17:23
  • I tried your solution, I tested it with this string just like that : myurl = new URL(":putyoururlhere") , but it don't throw me the malformedUrlException, but it thrower me a java.lang.StringIndexOutOfBoundsException and Force close the app Commented Feb 8, 2012 at 18:38

2 Answers 2

7

You can use the method isValidUrl() defined in android.webkit.URLUtil. For example

if (!URLUtil.isValidUrl("yourUrl") // do something 
Sign up to request clarification or add additional context in comments.

1 Comment

@Martin: it is usually best if your edits can be made as 'quiet' as possible; for example, I inlined the URL into the first reference of the method.
1

If you still want to use the apache commons validator library, then you just need to download the library and package it with your app.

3 Comments

thank you, however, I need to know if i should download the binary or the source file ? and also where to package it in my app ? Thank you for your time
Download the binary file and extract the commons-validator-1.4.0.jar file. Details on how to add the library to your app can be found here.
I realized that this class "org.apache.commons.validator" is deprecated, so I had rather import the new version : instead of that : import org.apache.commons.validator.UrlValidator; I did that : import org.apache.commons.validator.routines.UrlValidator;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.