在OkHttp3中,下面是不推荐的A
sslSocketFactory(SSLSocketFactory sslSocketFactory) 它被B取代:
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager).以下是我的问题:
更多信息:
创建SSLSocketFactory对象时,已经可以在
sslContext.init(KeyManager[] arg0, TrustManager[] arg1, SecureRandom arg2).例如,我通过执行以下操作获得一个SSLSocketFactory对象:
public SSLSocketFactory getSSLSocketFactory() {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(getKeyManager(), getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
}使用getTrustManager(),一种返回TrustManager[],的方法,该方法包含客户机应该信任的服务器证书。
现在,既然
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) 期望我提供一个X509TrustManager对象,我通过以下操作来处理这个问题:
OkHttpClient okClient = new OkHttpClient.Builder().sslSocketFactory(getSSLSocketFactory(), (X509TrustManager) getTrustManager()[0]).build();然而,我觉得这不是他们期望我们使用它的方式。因此,任何投入都是受欢迎的。
谢谢。
发布于 2019-09-01 14:39:47
该方法使用反射。原因在OkHttp文档中有说明。
/**
* Sets the socket factory used to secure HTTPS connections.
* If unset, the system default will be used.
*
* @deprecated [SSLSocketFactory] does not expose its [X509TrustManager], which is
* a field that OkHttp needs to build a clean certificate chain. This method
* instead must use reflection to extract the trust manager. Applications should
* prefer to call `sslSocketFactory(SSLSocketFactory, X509TrustManager)`,
* which avoids such reflection.
*/https://stackoverflow.com/questions/53201876
复制相似问题