在okhttp3中,以下内容已被弃用[a]:

    sslSocketFactory(SSLSocketFactory sslSocketFactory)

替换为[B]:
    sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager).

以下是我的问题:
X509TrustManager在[B]中有什么用途?
当在创建sslsocketfactory对象时已经可以指定trustmanager时,使用[b]而不是[a]有什么好处?
https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#sslSocketFactory-javax.net.ssl.SSLSocketFactory-
他们说在使用[b]时要避免反射,有人能解释一下吗?
更多信息:
创建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();

然而,我有一种感觉,这不是他们期望我们使用它的方式。所以欢迎任何意见。
谢谢。

最佳答案

该方法使用反射。原因在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/

10-10 19:14