6

在 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();

但是,我觉得这不是他们期望我们使用它的方式。因此,欢迎任何意见。

谢谢。

4

1 回答 1

0

该方法使用反射。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.
 */
于 2019-09-01T14:39:47.843 回答