Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to sslSocketFactory in Java10

I am using OkHttp and I need to ignore SSL errors for application debugging. This used to work in Java 8.

final TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }
    };

    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (Exception s) {
        s.printStackTrace();
    }
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    //
    //.sslSocketFactory(sslSocketFactory) throws error.
    client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory).build();

But in Java 9 and 10 I get this error.

java.lang.UnsupportedOperationException: clientBuilder.sslSocketFactory(SSLSocketFactory) not supported on JDK 9+

Is there another way to ignore OkHttp SSL errors in Java 9 and 10 without using sslSocketFactory?

like image 390
JCodes13 Avatar asked May 29 '18 23:05

JCodes13


1 Answers

Use sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

In your code example you construct a X509TrustManager, just pass it in along with the socket factory.

like image 110
Sean F Avatar answered Oct 20 '22 10:10

Sean F