问题描述
为了与我的 android 应用程序进行通信,我使用了 network-security-config.xml,它看起来像
<network-security-config>
<base-config>
<trust-anchors>
<certificates src="@raw/my_ca"/>
<certificates src="system"/>
</trust-anchors>
</base-config>
</network-security-config>
my_ca 在哪里 - 证书(.pem 文件)
在 API
解决方法
声明式网络安全配置已在 Android 7 (API 24) 中添加。在此之前,您必须以编程方式进行。不幸的是,这并不简单,步骤是:
- 将证书放入
KeyStore
- 创建一个
X509TrustManager
- 创建一个
SSLSocketFactory
- 构建
OkHttpClient
- 在
Retrofit
构建器中使用客户端
有 OkHttp recipe 描述了这一点。
似乎还有一个带有更简单 API 的 OkHttp extension :
val certificate = """-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE
""".decodeCertificatePem()
val certificates: HandshakeCertificates = HandshakeCertificates.Builder()
.addTrustedCertificate(certificate)
.addPlatformTrustedCertificates()
.build()
val client = OkHttpClient.Builder()
.sslSocketFactory(certificates.sslSocketFactory(),certificates.trustManager)
.build()
Retrofit.Builder()
.client(client)
...
.build()
.create(MyWebService::class.java)
构建 OkHttp 客户端的类似示例 in java