Java10 中 sslSocketFactory 的替代品

Alternative to sslSocketFactory in Java10

我正在使用 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,只需将其与套接字工厂一起传入即可。

问题是 sslSocketFactory() 的单参数版本已更改为抛出上述错误。您只需要重构一些东西并使用它的 2 参数版本,但您仍然可以使用覆盖的方法保持匿名 class。

以上代码经过重构后可以正常工作:

X509TrustManager x509TrustManager = 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[]{};
  }
};
     
final TrustManager[] trustAllCerts = new TrustManager[] {x509TrustManager};

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


// Since sslSocketFactory(sslSocketFactory) throws an error 
//  use sslSocketFactory(sslSocketFactory, x509TrustManager)
client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, x509TrustManager).build();