在Android P/9.0下 使用HttpUrlConnection进行http请求会出现以下异常:
java.net.UnknownServiceException: CLEARTEXT communication to ..... not permitted by network security policy
导致这种问题的原因是:
在Android P/9.0 系统的上,http网络请求是非加密的明文流量,会导致无法连接到网路,,https则不会受影响
解决方法:
(1) 在AndroidManifest.xml 文件,在 application 标签中添加:
android:usesCleartextTraffic="true"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
....
</application>
你也可以用下面方法实现:
在 res 下新增一个 xml 目录,然后创建一个xml 文件(名字自定),内容如下,意思是允许http网络权限
我的xml文件为:network_config.
<?xml version="1.0" encoding="utf-8"?>
<network-config>
<base-config cleartextTrafficPermitted="true" />
</network-config>
在AndroidManifest.xml文件下的application标签中增加属性
android:networkSecurityConfig="@xml/network_config"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:networkSecurityConfig="@xml/network_config"
android:theme="@style/AppTheme">
....
</application>
ok!!! 解决了 你也可以把网络请求改成 https ,不会出现上面错误