Alternative to sslSocketFactory in Java10

回眸只為那壹抹淺笑 提交于 2020-08-19 07:31:27

问题


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?


回答1:


Use sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

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



来源:https://stackoverflow.com/questions/50594350/alternative-to-sslsocketfactory-in-java10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!