How to check if URL is valid in Android

后端 未结 12 1329
轻奢々
轻奢々 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:24

    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

    0 讨论(0)
  • 2020-11-27 03:27
    new java.net.URL(String) throws MalformedURLException
    
    0 讨论(0)
  • 2020-11-27 03:33
    URLUtil.isValidUrl(url);
    

    If this doesn't work you can use:

    Patterns.WEB_URL.matcher(url).matches();
    
    0 讨论(0)
  • 2020-11-27 03:33
    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.

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

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

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