How to check if URL is valid in Android

后端 未结 12 1674
轻奢々
轻奢々 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: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;
    }
    

提交回复
热议问题