Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttpClient.Builder sslSocketFactory is deprecated

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

like image 206
fasal shah Avatar asked Oct 30 '22 17:10

fasal shah


1 Answers

You need a valid certificate. Create trusted OkHttpClient that trusts any ssl certificate. Try this code:

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

more info here: Now that SSLSocketFactory is deprecated on Android, what would be the best way to handle Client Certificate Authentication?

like image 109
oskarko Avatar answered Nov 15 '22 06:11

oskarko