在北京时间 2018 年 8 月 7 日,Google 发布的了 Android 9.0 (API 28),代号 “Pie”,其中一个新特性是:全部应用程序默认都使用 Https,这个会致使原 Http 请求无效。固然,开发人员能够将 targetSdkVersion 设置成 26 ,但今年的 Google play store 要求新提交的应用必须将 targetSdkVersion 设置成 28,就是说应用必须适配 Https。java
俗话说:上有政策,下有对策。这里将讨论如何解决 Android 9.0(API 级别 28) Http 适配问题。目前有三种解决方案:android
APP 改用 Https 请求(须要服务器支持)安全
targetSdkVersion 降到 27 如下(包含 27)服务器
根据 Android的网络安全性配置 自定义其网络安全设置网络
APP 将全部 Http 请求都换成 Https,这种是最完全的解决方式,也算是正规军线路,但这个工做量可不小,还须要服务器支持,即服务器的全部 Http 请求接口也都换成 Https,不然也是无效的,在新项目或重要的项目,仍是建议这么作。app
compileSdkVersion 26 defaultConfig { minSdkVersion 19 targetSdkVersion 26 testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" }
targetSdkVersion 降到 27 如下(包含 27),虽然 Google play store 对新应用要求 API 28 (2019.08 开始),但国内的各大应用平台,如 BAT 基本上只要求 API 26 便可,这一政策仍是去年末才生效,因此只作国内市场的话,将目标版本定为 26 是还能够持续一段时间的。gradle
若是项目是涉及海外市场,即必定要上 Google play store 又要使用 Http 接口,感受很矛盾的,固然了,也是有办法处理,经过配置网络安全设置可达到同样的效果。ui
build.gradle 中的目标 API 设置:spa
compileSdkVersion 28 defaultConfig { minSdkVersion 19 targetSdkVersion 28 testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" }
在清单文件 AndroidManifest.xml 的 application 标签里面设置 networkSecurityConfig 属性以下:code
<application ... android:allowBackup="true" android:icon="${app_icon}" android:label="@string/app_name" android:networkSecurityConfig="@xml/network_security_config" ...> </application>
在 res 目录下新建 xml 文件夹,建立 xml 文件 network_security_config.xml 以下:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true"/> </network-security-config>
或
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> </trust-anchors> </base-config> </network-security-config>