当前位置: 代码迷 >> 综合 >> retrofit调用https接口报错java.security.cert.CertPathValidatorException
  详细解决方案

retrofit调用https接口报错java.security.cert.CertPathValidatorException

热度:76   发布时间:2023-12-12 11:57:05.0

有些https接口,用retrofit+okhttps调用会报错:javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

解决方法是在每次调用接口前调用以下方法:

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;public static void setNoCertificates() {try {SSLContext sc = SSLContext.getInstance("SSL");X509TrustManager trustManager = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}};X509TrustManager[] trustManagers = new X509TrustManager[]{trustManager};sc.init(null, trustManagers, new SecureRandom());httpClient.sslSocketFactory(sc.getSocketFactory(), trustManager).hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}}).build();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}}