Android 9.0 Http配置

Posted by OOFTF Blog on April 30, 2021

在Android9异常使用Http请求会抛出以下异常

1
2
3
4
5
6
HttpUrlConnection:
W/System.err: java.io.IOException: Cleartext HTTP traffic to ** not permitted.

OKHttp:
W/System.err: java.net.UnknownServiceException: CLEARTEXT communication to ** not permitted by network security policy.

兼容Http方案

xml 文件下添加 res/xml/network_security_config.xml

1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

AndroidManifest文件内添加

1
2
3
<application
    android:networkSecurityConfig="@xml/network_security_config">
</application>

扩展:网络安全配置

限制可信 CA 集

请求 secure.example.com 和 cdn.example.com 域名时,信任 trusted_roots CA

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">secure.example.com</domain>
        <domain includeSubdomains="true">cdn.example.com</domain>
        <trust-anchors>
            <certificates src="@raw/trusted_roots"/>
        </trust-anchors>
    </domain-config>
</network-security-config>

配置APP全局可信任CA

App所有请求信任 system 和 extracas CA

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="@raw/extracas"/>
            <certificates src="system"/>
        </trust-anchors>
    </base-config>
</network-security-config>

配置是否强制使用SSL认证

访问 secure.example.com 域名,允许使用非SSL请求

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">secure.example.com</domain>
        </domain-config>
    </network-security-config>