Android 9.0 (API 28) Http 请求解决方案

在北京时间 2018 年 8 月 7 日,Google 发布的了 Android 9.0 (API 28),代号 “Pie”,其中一个新特性是:所有应用程序默认都使用 Https,这个会导致原 Http 请求无效。当然,开发人员可以将 targetSdkVersion 设置成 26 ,但今年的 Google play store 要求新提交的应用必须将 targetSdkVersion 设置成 28,就是说应用必须适配 Https。

俗话说:上有政策,下有对策。这里将讨论如何解决 Android 9.0(API 级别 28) Http 适配问题。目前有三种解决方案:

  • APP 改用 Https 请求(需要服务器支持)

  • targetSdkVersion 降到 27 以下(包含 27)

  • 根据 Android的网络安全性配置 自定义其网络安全设置

一、APP 改用 https 请求(需要服务器支持)

APP 将所有 Http 请求都换成 Https,这种是最彻底的解决方式,也算是正规军线路,但这个工作量可不小,还需要服务器支持,即服务器的所有 Http 请求接口也都换成 Https,否则也是无效的,在新项目或重要的项目,还是建议这么做。

二、targetSdkVersion 降到 27 以下(包含 27)

    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 是还可以持续一段时间的。

三、自定义其网络安全设置

如果项目是涉及海外市场,即一定要上 Google play store 又要使用 Http 接口,感觉很矛盾的,当然了,也是有办法处理,通过配置网络安全设置可达到一样的效果。

build.gradle 中的目标 API 设置:

    compileSdkVersion 28
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 28
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

在清单文件 AndroidManifest.xml 的 application 标签里面设置 networkSecurityConfig 属性如下:

    <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>