How to check if URL is valid in Android
Asked Answered
R

12

139

Is there a good way to avoid the "host is not resolved" error that crashes an app? Some sort of a way to try connecting to a host ( like a URL ) and see if it's even valid?

Retrench answered 5/2, 2011 at 4:10 Comment(1)
how are you connecting to the host?Coquetry
S
254

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.

Sidman answered 18/12, 2012 at 11:29 Comment(5)
isValidUrl returns false for the following URL, although the device seems happy enough with it (it's missing the double slash after file:). "file:/storage/emulated/0/Android/data/com.samsung.android.app.pinboard/files/ClipData/Screenshot_NormarAppImage.png"Fauch
I would not rely on this method, because it doesn't perform deep validation, only most simple WebView cases. See sourceInebriety
Better answer: #5618249Inebriety
it seems that as long as it has http:// or https:// it will return trueLotuseater
Would this help avoid urls like mailto: [email protected] and about:blank#blockedAphonia
P
105
URLUtil.isValidUrl(url);

If this doesn't work you can use:

Patterns.WEB_URL.matcher(url).matches();
Pray answered 27/1, 2014 at 10:43 Comment(3)
Does this not just check the pattern rather than whether the URL is actually active?Foreshore
As far as i know,if we need to check whether url is actually pinging or not we should manually check for that using HttpURLConnection class.Pray
Use the second option if you need to check urls without schema. URLUtil.isValidUrl will return false if schema is not added.Ol
F
31

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;
}
Fumigate answered 6/12, 2016 at 14:53 Comment(0)
S
9

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
}
Skyrocket answered 10/9, 2018 at 6:53 Comment(0)
D
5

Just add this line of code:

Boolean isValid = URLUtil.isValidUrl(url) && Patterns.WEB_URL.matcher(url).matches();       
Darbie answered 4/4, 2020 at 14:51 Comment(0)
E
4

Wrap the operation in a try/catch. There are many ways that a URL can be well-formed but not retrievable. In addition, tests like seeing if the hostname exists doesn't guarantee anything because the host might become unreachable just after the check. Basically, no amount of pre-checking can guarantee that the retrieval won't fail and throw an exception, so you better plan to handle the exceptions.

Emilioemily answered 5/2, 2011 at 4:35 Comment(2)
I don't mind handling the exception but how do I prevent the app from crashing due to that very exception?Retrench
@Retrench Err, catch the exception? What else could 'handling the exception' possibly mean?Delphine
T
4

I have tried a lot of methods.And find that no one works fine with this URL:

Now I use the following and everything goes well.

public static boolean checkURL(CharSequence input) {
    if (TextUtils.isEmpty(input)) {
        return false;
    }
    Pattern URL_PATTERN = Patterns.WEB_URL;
    boolean isURL = URL_PATTERN.matcher(input).matches();
    if (!isURL) {
        String urlString = input + "";
        if (URLUtil.isNetworkUrl(urlString)) {
            try {
                new URL(urlString);
                isURL = true;
            } catch (Exception e) {
            }
        }
    }
    return isURL;
}
Tips answered 30/4, 2014 at 6:53 Comment(0)
P
4
import okhttp3.HttpUrl;
import android.util.Patterns;
import android.webkit.URLUtil;

            if (!Patterns.WEB_URL.matcher(url).matches()) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (HttpUrl.parse(url) == null) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (!URLUtil.isValidUrl(url)) {
                error.setText(R.string.wrong_server_address);
                return;
            }

            if (!url.substring(0,7).contains("http://") & !url.substring(0,8).contains("https://")) {
                error.setText(R.string.wrong_server_address);
                return;
            }
Peasecod answered 27/10, 2017 at 8:39 Comment(0)
E
4

In my case Patterns.WEB_URL.matcher(url).matches() does not work correctly in the case when I type String similar to "first.secondword"(My app checks user input). This method returns true.

URLUtil.isValidUrl(url) works correctly for me. Maybe it would be useful to someone else

Elysha answered 28/11, 2017 at 12:16 Comment(1)
Patterns.WEB_URL.matcher(url).matches() is failing on my end too, I think because the link has no wwwand only https.Kentkenta
C
3

You cans validate the URL by following:

Patterns.WEB_URL.matcher(potentialUrl).matches()
Continually answered 26/12, 2018 at 14:33 Comment(0)
M
3
public static boolean isURL(String text) {
    String tempString = text;

    if (!text.startsWith("http")) {
        tempString = "https://" + tempString;
    }

    try {
        new URL(tempString).toURI();
        return Patterns.WEB_URL.matcher(tempString).matches();
    } catch (MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
        return false;
    }
}

This is the correct sollution that I'm using. Adding https:// before original text prevents text like "www.cats.com" to be considered as URL. If new URL() succeed, then if you just check the pattern to exclude simple texts like "https://cats" to be considered URL.

Munford answered 5/7, 2019 at 11:39 Comment(0)
M
0
new java.net.URL(String) throws MalformedURLException
Marcellemarcellina answered 29/11, 2018 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.