在OkHttp3中,以下内容已被弃用[A]:
sslSocketFactory(SSLSocketFactory sslSocketFactory)
替换为[B]:
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager).
以下是我的问题:
[B]中的X509TrustManager有什么用?
当创建SSLSocketFactory对象时已经可以指定TrustManager时,使用[B]而不是[A]有什么优势?
在https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#sslSocketFactory-javax.net.ssl.ssl套接字工厂-他们谈到在使用[B]时避免反思,有人能解释一下吗?
更多信息:
创建SSLSocketFactory对象时,已经可以在中指定trustManager
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();
然而,我觉得这不是他们期望我们使用它的方式。所以任何意见都是受欢迎的。
谢谢。
该方法使用反射。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.
*/