使用API​​时未找到证书路径的信任锚

时间:2018-04-26 15:56:57

标签: android

我正在制作新闻应用,而我正在使用newsapi.org获取新闻。我在模拟器和一台设备上尝试了我的应用程序并且它正常工作但后来我在另一台设备上尝试了它并且我收到此错误:引起:java.security.cert.CertificateException:java.security.cert.CertPathValidatorException:Trust anchor找不到证书路径。有谁知道为什么会发生这种情况? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

将此方法与Retrofit中的REtrofit 2一起使用,将其作为客户端添加,如图中所示

public static OkHttpClient.Builder getUnsafeOkHttpClient() {

        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    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[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

enter image description here