onFailure: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust

http请求报错

onFailure: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

看得出来后端签发的SSL证书应该是有问题的

解决的方法

方法一(根本解决方法):后端获取合法合规的证书

方法二(临时办法):发起网络请求时暂时跳过证书认证的过程,完成接口测试

 private static SSLSocketFactory createInsecureSSLSocketFactory() {
        try {
            TrustManager[] trustAllCerts = new 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];
                        }
                    }
            };

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static X509TrustManager createTrustAllManager() {
        return 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];
            }
        };
    }

使用方法:

okhttp发起请求时

 OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.MINUTES)//设置访问超时时间
                .readTimeout(5, TimeUnit.MINUTES)
                .writeTimeout(5, TimeUnit.MINUTES)
                .sslSocketFactory(createInsecureSSLSocketFactory(), createTrustAllManager())
                .hostnameVerifier((hostname, session) -> true)
                .build();

你可能感兴趣的:(android,ssl,java,网络协议)