Android 网络请求绕过 HTTPS 限制

yuan
·

targetSDK 升 28 之后,Android 强制要求网络请求必须使用 https 协议。在公网服务器上这事情好办,直接开启 https 支持即可。而且现在也没有什么网站是不支持 https 的了吧。

但在自己的电脑上开发和调试 Android 程序时,这个限制就不太方便。可能 Google 也考虑到了这一点,因此提供了一个方法

首先开启本地服务器,假设其运行在 3000 端口上。

新建一个 res/xml/network_security_config.xml 文件,并在 AndroidManifest.xml 当中引用它:

<?xml version="1.0" encoding="utf-8"?>
<!-- AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name.here>
    <application
        android:networkSecurityConfig="@xml/network_security_config"
        ....>
        <activity .../>
</manifest>

network_security_config.xml 内容如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- network_security_config.xml -->
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <!-- 这里配置上域名白名单 -->
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

然后把手机的 3000 端口映射到开发机的 3000 端口。

adb reverse tcp:3000 tcp:3000

最后,将你代码中访问服务的域名改为 localhost 即可。

补充:虽然非常不建议,但如果你想让整个 APP 访问任何网络都不受这个 https 协议的限制,可以这么做:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true"></base-config>
</network-security-config>
1
社区准则 博客 联系 社区 状态
主题