上一篇提過,爲了能夠Charles能夠抓包,在代碼裏面添加了
android:networkSecurityConfig="@xml/network_security_config"
爲什麼要添加這個?
我在官方的文檔找到了答案
網絡安全性配置特性讓應用可以在一個安全的聲明性配置文件中自定義其網絡安全設置,而無需修改應用代碼。可以針對特定域和特定應用配置這些設置。此特性的主要功能如下所示:
- 自定義信任錨:針對應用的安全連接自定義哪些證書頒發機構 (CA) 值得信任。例如,信任特定的自簽署證書或限制應用信任的公共 CA 集。
- 僅調試重寫:在應用中以安全方式調試安全連接,而不會增加已安裝用戶的風險。
- 明文通信選擇退出:防止應用意外使用明文通信。
- 證書固定:將應用的安全連接限制爲特定的證書。
具體細節可以參考:
https://developer.android.google.cn/training/articles/security-config.html
我大致歸類了一下:
1. 如果你設置了代理去抓包一下幾種配置都是沒有問題的:
配置自定義 CA
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">example.com</domain>
<trust-anchors>
<certificates src="@raw/my_ca"/>
</trust-anchors>
</domain-config>
</network-security-config>
限制可信 CA 集
<?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>
信任附加 CA
<?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>
以上配置,如果沒有設置代理,會存在一種風險:移除代理後,會出現網絡訪問失敗的情況,這個時候需要你把AndroidMainfest.xml裏面的android:networkSecurityConfig給去掉即可。
2.如果不想把AndroidMainfest.xml的安全設置去掉也是可以的:
使用以下方法:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<debug-overrides>
<trust-anchors>
<certificates src="@raw/debug_cas"/>
</trust-anchors>
</debug-overrides>
</network-security-config>
這樣就不會影響到網絡訪問了。