Alternative to sslSocketFactory in Java10

后端 未结 2 570
予麋鹿
予麋鹿 2020-12-19 10:38

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 TrustManag         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 11:04

    The issue is that the single parameter version of sslSocketFactory() has been changed to throw the above error. You just need to refactor somethings and use the 2 parameter version of it, but you can still keep your anonymous class with the overridden methods.

    Here is the above code refactored to work:

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

提交回复
热议问题