How to check if URL is valid in Android

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

提交回复
热议问题