In OkHttp3, the following is deprecated [A]:
sslSocketFactory(SSLSocketFactory sslSocketFactory)
It is replaced by [B]:
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager).
Here are my questions:
What is the use of X509TrustManager in [B] ?
What are the advantages of using [B] rather than [A] when a TrustManager can already be specified when creating a SSLSocketFactory object?
In https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#sslSocketFactory-javax.net.ssl.SSLSocketFactory- they talk about avoiding reflection when using [B], could somebody explain?
More info:
When creating a SSLSocketFactory object, it is already possible to specify a trustManager in
sslContext.init(KeyManager[] arg0, TrustManager[] arg1, SecureRandom arg2).
For example, I get a SSLSocketFactory object by doing:
public SSLSocketFactory getSSLSocketFactory() {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(getKeyManager(), getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
}
With getTrustManager() a method that returns a TrustManager[], which contains the servers' certificate the client should trust.
Now, since
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
expects me to provide a X509TrustManager object, I deal with this by doing:
OkHttpClient okClient = new OkHttpClient.Builder().sslSocketFactory(getSSLSocketFactory(), (X509TrustManager) getTrustManager()[0]).build();
However, I have the feeling this is not how they were expecting us to use it. So any inputs are welcome.
Thanks.
The method uses reflection. The reason is stated in the 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.
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With