Android 9.0/P okhttp网络请求出错

今天做项目时意外发现,已经在AndroidManifest.xml申请网络权限,在8.0以下的系统中网络访问正常,但是9.0中出现网络请求失败。

如图(左是荣耀6x   Android8.0,右是一加5   Android9.0):

      

 出现这个错误的原因是:从 Android 9 开始,默认情况下该内容库已从 bootclasspath 中移除且不可用于应用。且Android P 限制了明文流量的网络请求,非加密的流量请求都会被系统禁止掉。

解决方案

在res目录下新建一个xml目录,在xml目录下新建network_security_config.xml文件,

  插入以下代码

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

编辑 AndroidManifest.xml节点application

插入代码:

 android:networkSecurityConfig="@xml/network_security_config"

成功解决,以下图为证

对了,这是使用okhttp3才会出现的,使用httpURLConnectio则不会出现这个问题

原文地址:https://www.cnblogs.com/inthecloud/p/10972943.html