在 OkHttp3 中,以下内容已弃用[A]:
sslSocketFactory(SSLSocketFactory sslSocketFactory)
它被替换为 [B]:
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager).
这是我的问题:
[B] 中 X509TrustManager 的用途是什么?
当一个可以在创建SSLSocketFactory 对象时指定TrustManager 吗?
在https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#sslSocketFactory-javax.net.ssl.SSLSocketFactory- 他们谈论在使用 [B] 时避免反射,有人可以解释一下吗?
更多信息:
在创建SSLSocketFactory对象时,已经可以在
中指定一个trustManagersslContext.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[],其中包含客户端应该信任的服务器证书。 p>
现在,因为
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
期望我提供一个 X509TrustManager 对象,我通过以下方式处理:
OkHttpClient okClient = new OkHttpClient.Builder().sslSocketFactory(getSSLSocketFactory(), (X509TrustManager) getTrustManager()[0]).build();
但是,我觉得这不是他们期望我们使用它的方式。所以欢迎任何意见。
谢谢。
最佳答案
该方法使用反射。 OkHttp documentation 中说明了原因:
/**
* 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.
*/
关于java - OkHttp3 中的 SSLSocketFactory 和 TrustManager 冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53201876/