Android 9.0 网络请求适配
2019-03-25 本文已影响85人
明明可以不写代码
9.0要求使用安全的网络访问,如果项目使用的是http请求方式而非https,请求会失败。
解决方案:
一、APP改用https请求
这种方式需要接口去协调,把请求域名改为https。
二、targetSdkVersion 降到27以下
三、在 res 下新增一个 xml 目录,然后创建一个名为:network_security_config.xml 文件(名字自定) ,内容如下,大概意思就是允许开启http请求。
<?xml version="1.0" encoding="utf-8"?>
<!--Android 9.0 https请求适配-->
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
然后在APP的AndroidManifest.xml文件下的application标签增加以下属性:
android:networkSecurityConfig="@xml/network_security_config"
新增问题:上一个 xml 的配置只是解决了自己应用使用 okhhtp3 的问题。现在发现 OSS 上传图片也无法成功,一样是因为不安全的网络访问导致的,把 xml 文件的写法改成这样:
<?xml version="1.0" encoding="utf-8"?>
<!--Android 9.0 https请求适配-->
<network-security-config>
<!--<base-config cleartextTrafficPermitted="true" />-->
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">你的服务端接口地址</domain>
<domain includeSubdomains="true">你的 OSS 路径</domain>
</domain-config>
</network-security-config>
需要注意的是:你的服务端接口地址不要加 http:// 前缀,如果是 ip 地址,还不能加端口号。
再次新增问题:
发现讯飞和高德地图在9.0的设备上也会失效。高德地图日志打印网络异常,因此判断也是网络安全的原因。故而凡是项目中用到需要请求网络的第三方 SDK ,都需要做出对应的适配。所以为了避免麻烦,还是暂时先把 targetSdkVersion 降到 27 吧。