最近app提交测试的时候发现在9.0版本上无法访问网络,报的异常如下
CLEARTEXT communication to "" not permitted by network security policy。
查阅资料之后发现是因为加密的问题。Android P 限制了非加密的流量请求。
解决方法:
1.在res下创建一个xml的子目录,然后创建一个名为:network.xml的文件。
2.在文件中设置cleartextTrafficPermitted为开启状态。
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
3.在AndroidManifest 文件中加入该设置
<application
android:name=".base.App"
android:allowBackup="true"
android:icon="@mipmap/login_logo"
android:label="@string/app_name"
android:roundIcon="@mipmap/login_logo"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network"
tools:ignore="GoogleAppIndexingWarning,UnusedAttribute">
这样就可以解决这个报错。
当然,其实Android P 是提倡我们使用https. 如果把请求都换成https ,不用这些设置就可以了。