gpt4 book ai didi

安卓 java.net.UnknownHostException : Unable to resolve host

转载 作者:行者123 更新时间:2023-11-29 18:44:38 26 4
gpt4 key购买 nike

因此,我正在尝试向 IP 地址发送 POST 请求,但在此之前我发现了一个问题。为了检查是否有有效的互联网连接,我在创建 Activity 时调用了以下方法:

public void checkInternectConnection() {
AsyncTask.execute(() -> {

try {
InetAddress inAddress = InetAddress.getByName("https://google.com");
if (inAddress.equals("")) {
networkAvilable = true;
} else {
networkAvilable = false;
}
} catch (Exception e) {
e.printStackTrace();
networkAvilable = false;
}
});
}

执行这段代码时,它总是捕获异常java.net.UnkonwnHostException: Unable to resolve host "https://google.com": No address associated with hostname.

我搜索了错误,我所能找到的只是该应用程序没有互联网权限,但我在 android list 中已经拥有该权限 ( <uses-permission android:name="android.permission.INTERNET" /> )

我也试过 http://google.com而不是 https , 但没有任何效果。

有什么想法吗?

最佳答案

您需要像这样检查互联网连接:

private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

return cm.getActiveNetworkInfo() != null;
}

在 list 中

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

此方法实际上检查设备是否已连接到互联网(有可能它已连接到网络但未连接到互联网)。

public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");

} catch (Exception e) {
return false;
}
}

关于安卓 java.net.UnknownHostException : Unable to resolve host,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com