解决Android P/9.0 系统 网络请求错误

在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  ,不会出现上面错误

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值