错误套接字超时异常连接到谷歌在安卓



我的应用程序(Android(的连接有问题。我正在使用以下代码来检查我是否有互联网连接。

ConnectivityManager cm = (ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setRequestProperty("User-Agent", "test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(5000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (IOException e) {
Log.i("warning", "Error checking internet connection", e);
return false;
}
}

尝试几次后,我遇到问题是我正在对"www.google.com"执行ping操作。 我不明白为什么会这样。在我的项目中,这段代码在过去 2 年里一直很好。

如果您要在最新版本的 android 上对此进行测试,则需要验证是否已将域列入白名单。您应该阅读以下内容: https://developer.android.com/training/articles/security-config

作为快速修复,您可以将以下属性添加到应用程序标记:

android:usesCleartextTraffic="true"

最新更新