android java.net.UnknownHostException: Unable to resolve host

纵然是瞬间 提交于 2021-02-08 08:12:02

问题


So, I'm trying to send POST requests to an IP adress, but I've found a problem way before that. To check if there's a working connection to the internet I have the following method called when creating the 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;
            }
        });
}

When this code is executed, it always catches the exception java.net.UnkonwnHostException: Unable to resolve host "https://google.com": No address associated with hostname.

I've serched the error and all I can find is that the app doasn't have Internet permissions, but I have in the android manifest that permission already ( <uses-permission android:name="android.permission.INTERNET" />)

I've also tried with http://google.com instead of https, but nothing works.

Any ideas?


回答1:


You need to check internet connection like this:

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

    return cm.getActiveNetworkInfo() != null;
}

In manifest

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

This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

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;
    }
}


来源:https://stackoverflow.com/questions/52257063/android-java-net-unknownhostexception-unable-to-resolve-host

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!