OkHttpClient.Builder sslSocketFactory is deprecated

时间:2016-11-09 05:33:15

标签: android retrofit2 okhttp3

I'm trying to make https calls using (retrofit 2.0, okhttp3) I have already included ssl certificate and it works fine with
OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(getSSLConfig());
but it shows sslSocketFactory(getSSLConfig()) as deprecated and provides other option
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
I wanted to update my code and use new option instead of deprecated method I searched on net but could not find any good reference. If any one can provide some good reference to this issue will be very helpful

1 个答案:

答案 0 :(得分:1)

您需要有效的证书。创建信任任何ssl证书的受信任的OkHttpClient。试试这段代码:

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { trustManager }, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, trustManager);

此处有更多信息:Now that SSLSocketFactory is deprecated on Android, what would be the best way to handle Client Certificate Authentication?