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
You cans validate the URL by following:
Patterns.WEB_URL.matcher(potentialUrl).matches()
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.
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;
}
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.
Just add this line of code:
Boolean isValid = URLUtil.isValidUrl(url) && Patterns.WEB_URL.matcher(url).matches();
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;
}