android java.net.UnknownHostException:无法解析主机 [英] android java.net.UnknownHostException: Unable to resolve host

查看:77
本文介绍了android java.net.UnknownHostException:无法解析主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试将POST请求发送到IP地址,但是在此之前我发现了一种问题的解决方法.要检查互联网连接是否正常,在创建活动"时,我调用了以下方法:

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

执行此代码时,它始终会捕获异常 java.net.UnkonwnHostException:无法解析主机"https://google.com":没有与主机名关联的地址.

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.

我已经解决了该错误,我只能找到该应用没有互联网权限,但是我在android清单中已经拥有该权限(< uses-permission android:name ="android.permission.INTERNET"/> )

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" />)

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

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

有什么想法吗?

推荐答案

您需要像这样检查Internet连接:

You need to check internet connection like this:

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

    return cm.getActiveNetworkInfo() != null;
}

清单中

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

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

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

这篇关于android java.net.UnknownHostException:无法解析主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆