How to check if URL is valid in Android

后端 未结 12 1328
轻奢々
轻奢々 2020-11-27 02:31

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 vali

相关标签:
12条回答
  • 2020-11-27 03:13

    You cans validate the URL by following:

    Patterns.WEB_URL.matcher(potentialUrl).matches()
    
    0 讨论(0)
  • 2020-11-27 03:14

    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.

    0 讨论(0)
  • 2020-11-27 03:15
    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;
                }
    
    0 讨论(0)
  • 2020-11-27 03:22

    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.

    0 讨论(0)
  • 2020-11-27 03:22

    Just add this line of code:

    Boolean isValid = URLUtil.isValidUrl(url) && Patterns.WEB_URL.matcher(url).matches();       
    
    0 讨论(0)
  • 2020-11-27 03:24

    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;
    }
    
    0 讨论(0)
提交回复
热议问题