android Logcat报错 CLEARTEXT communication to 192.168.1.2 not permitted by network security policy

之前做项目都是在模拟器上调试,这几天使用真机调试,由于之前模拟器的android版本很低,所有没用啥错误,我的手机的android版本是Android10,所以就出错了,调用okhttp没用返回数据,我的界面啥也没有。然后查看Logcat信息
Logcat信息:
在这里插入图片描述
原因:Android P 限制了明文流量的网络请求,非加密的流量请求都会被系统禁止掉。
如果当前应用的请求是 htttp 请求,而非 https ,这样就会导系统禁止当前应用进行该请求,如果 WebView 的 url 用 http 协议,同样会出现加载失败,https 不受影响。

为此,OkHttp3 做了检查,所以如果使用了明文流量,默认情况下,在 Android P 版本 OkHttp3 就抛出异常: CLEARTEXT communication to " + host + " not permitted by network security policy

if (!Platform.get().isCleartextTrafficPermitted(host)) {
    
    
      throw new RouteException(new UnknownServiceException(
          "CLEARTEXT communication to " + host + " not permitted by network security policy"));
 }

解决方法:
在res新建文件夹xml
新建文件network_security_config.xml文件

<?xml version ="1.0" encoding ="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

在AndroidMainfest.xml文件夹配置android:networkSecurityConfig="@xml/network_security_config"

 <application
        android:name=".common.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/MainTheme" android:networkSecurityConfig="@xml/network_security_config">

问题解决

猜你喜欢

转载自blog.csdn.net/rj2017211811/article/details/107266598