编程语言
首页 > 编程语言> > Java10中sslSocketFactory的替代

Java10中sslSocketFactory的替代

作者:互联网

我正在使用OkHttp,并且需要忽略SSL错误以进行应用程序调试.这曾经在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中,我得到了这个错误.

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

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

解决方法:

使用sslSocketFactory(SSLSocketFactory sslSocketFactory,X509TrustManager trustManager)

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

标签:okhttp3,java-10,ssl,java-9,java
来源: https://codeday.me/bug/20191025/1926340.html