java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. 异常处理
异常描述
由于在本地测试环境调试过程中,本地服务器IP发生变更且新增自定义证书,这个导致了app内置的访问网址调用时会报如标题所示内容。
异常原因分析
OkHttp等调用过程中,使用https打头的url访问服务器过程中,app会自动确认服务器是否含有系统 CA认证,若服务器无系统承认的 CA认证 app在访问过程中即会报 Trust anchor for certification path not found.。 此时需要在app内部集成本地服务器的自定义网络安全证书,或将证书安装到需要使用的测试机上。
解决方案
1. app内部集成自定义网络安全证书
网络安全配置功能需要使用一个 XML 文件,我们可以在该文件中指定应用的网络安全设置。在设置中指定文件位置清单:
1)在res文件夹下新建一个raw 文件夹,将证书xx.pem文件放置于此文件夹下, 我这里是debug_cas.pem。
2)在res文件夹下新建xml文件夹,并新增一个xml文件用于配置网络安全参数(即额外证书指向),此处我是用的是network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
<base-config>
<trust-anchors>
<certificates src="@raw/debug_cas"/>
<certificates src="system"/>
</trust-anchors>
</base-config>
</network-security-config>
其中 certificates src="@raw/debug_cas" 表示我们上一步自定义证书位置,certificates src=“system” 表示系统默认证书。此处功能即为增加app允许访问除系统默认ca认证之外的其他自定义证书。
3)最后一步需要在 AndroidMainifest.xml(主配置) 文件中添加 android:networkSecurityConfig ,表示变更网络配置。代码如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config"
... >
...
</application>
</manifest>
参考官方文档:https://developer.android.google.cn/training/articles/security-config?hl=zh-cn#TrustingAdditionalCas
2. 在测试机上安装证书(此处参考他人文档)
https://blog.csdn.net/u014540814/article/details/80518208
更多推荐
所有评论(0)