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

有些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() {
                @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];
                }
            };
            X509TrustManager[] trustManagers = new X509TrustManager[]{
                    trustManager
            };
            sc.init(null, trustManagers, new SecureRandom());
            httpClient.sslSocketFactory(sc.getSocketFactory(), trustManager).hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

 

你可能感兴趣的:(retrofit)