kotlin okhttp3怎么自动从https网站保存cer证书到本地 给出示例代码
时间: 2023-03-24 14:03:58 浏览: 247
证书一键下载,可以一键生成localhost的https证书,方便本地调试使用
你可以使用OkHttp的CertificatePinner类来验证证书,然后使用OkHttp的SSLContext来保存证书。以下是示例代码:
```
// 创建OkHttpClient
OkHttpClient client = new OkHttpClient.Builder()
.certificatePinner(new CertificatePinner.Builder()
.add("example.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
.build())
.build();
// 获取证书
CertificatePinner certificatePinner = client.certificatePinner();
Set<String> pins = certificatePinner.pins("example.com");
// 保存证书
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
for (String pin : pins) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream inputStream = new ByteArrayInputStream(Base64.decode(pin.split("/")[1], Base64.DEFAULT));
X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
keyStore.setCertificateEntry(cert.getSubjectDN().toString(), cert);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
// 创建OkHttpClient
OkHttpClient newClient = client.newBuilder()
.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagerFactory.getTrustManagers()[])
.build();
```
注意:这里的证书是使用Base64编码的,你需要将证书的内容替换成你自己的证书内容。
阅读全文