【发布时间】:2018-11-29 02:59:36
【问题描述】:
出于测试目的,我需要模拟客户端 api 请求。我们的服务器现在使用 https,建议我使用 OkHttpClient 而不是我们原来的 BaseHttpClient 实现。我发现我需要将.sslSocketFactory(sslSocketFactory, x509TrustManager) 添加到我的客户端构建器中,并且我还找到了加载证书的有用代码:
private X509TrustManager trustManagerForCertificates(InputStream in)
{
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
char[] password = "password".toCharArray(); // Any password will work.
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
return (X509TrustManager) trustManagers[0];
}
我的问题是我的证书有一个密钥,我找不到将.crt 和.key 文件的内容成对提供的方法。如果我要卷曲它,我可以做到
curl --tlsv1.2 --insecure -v --key ./client.key --cert ./client.crt https://myserver/api/request
有没有办法用 OkHttp 做类似的事情?还是我必须使用现有证书及其密钥生成新证书?
【问题讨论】: