Java10中sslSocketFactory的替代

Java10中sslSocketFactory的替代

本文介绍了Java10中sslSocketFactory的替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用OkHttp,我需要忽略SSL错误以进行应用程序调试.这曾经在Java 8中可用.

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

但是在Java 9和10中,我会收到此错误.

But in Java 9 and 10 I get this error.

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

是否有另一种方法可以在不使用sslSocketFactory的情况下忽略Java 9和10中的OkHttp SSL错误?

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

推荐答案

使用sslSocketFactory(SSLSocketFactory sslSocketFactory,X509TrustManager trustManager)

Use sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

在您的代码示例中,您构造了一个X509TrustManager,只需将其与套接字工厂一起传递即可.

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

这篇关于Java10中sslSocketFactory的替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:38