Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if URL is valid in Android

People also ask

How can I check if an android URL is valid?

Use URLUtil to validate the URL as below. It will return True if URL is valid and false if URL is invalid.

How do you check if a URL is valid or not?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

What is URL valid?

A URL is a valid URL if at least one of the following conditions holds: The URL is a valid URI reference [RFC3986]. The URL is a valid IRI reference and it has no query component. [RFC3987] The URL is a valid IRI reference and its query component contains no unescaped non-ASCII characters.


Use URLUtil to validate the URL as below.

 URLUtil.isValidUrl(url)

It will return True if URL is valid and false if URL is invalid.


URLUtil.isValidUrl(url);

If this doesn't work you can use:

Patterns.WEB_URL.matcher(url).matches();

I would use a combination of methods mentioned here and in other Stackoverflow threads:

public static boolean IsValidUrl(String urlString) {
    try {
        URL url = new URL(urlString);
        return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
    } catch (MalformedURLException ignored) {
    }
    return false;
}

If you are using from kotlin you can create a String.kt and write code bellow:

fun String.isValidUrl(): Boolean = Patterns.WEB_URL.matcher(this).matches()

Then:

String url = "www.yourUrl.com"
if (!url.isValidUrl()) {
    //some code
}else{
   //some code
}