当前位置: 首页 > 工具软件 > Packet.Net > 使用案例 >

Retrofit中解决javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException

壤驷彦
2023-12-01

第一步:

//创建OkHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(ApiService.DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(ApiService.DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(ApiService.DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(httpLoggingInterceptor)//添加日志拦截器
                .addInterceptor(new TokenInterceptor());//添加token拦截器
		<!---注意此处---->
        SSLContext sslContext = SSLContextUtil.getDefaultSLLContext();
        if (sslContext != null) {
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(socketFactory);
        }
        builder.hostnameVerifier(SSLContextUtil.HOSTNAME_VERIFIER);
        OkHttpClient mOkHttpClient = builder.build();

第二步:

/**
 * https 证书工具
 *
 * @author Yan Zhenjie.
 */
public class SSLContextUtil {

  /**
   * 如果不需要https证书.(NoHttp已经修补了系统的SecureRandom的bug)。
   */
  public static SSLContext getDefaultSLLContext() {
    SSLContext sslContext = null;
    try {
      sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, new TrustManager[] {trustManagers}, new SecureRandom());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return sslContext;
  }

  /**
   * 信任管理器
   */
  private static TrustManager trustManagers = new X509TrustManager() {

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {}

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
      return new X509Certificate[0];
    }
  };

  /**
   * 域名验证
   */
  public static final HostnameVerifier HOSTNAME_VERIFIER = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
      return true;
    }
  };

}
 类似资料: