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

前端 未结 11 750
清酒与你
清酒与你 2020-11-27 15:59

I am using Retrofit to access my REST API. However, when I put my API behind ssl and access it by http://myhost/myapi then I get this error:

Do I need t

11条回答
  •  爱一瞬间的悲伤
    2020-11-27 16:46

    After a some research i found the way to bypass ssl error Trust anchor for certification path not found. This might be not a good way to do but you can use it for a testing purpose.

     private HttpsURLConnection httpsUrlConnection( URL urlDownload) throws Exception {
      HttpsURLConnection connection=null;
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
    
                @SuppressLint("TrustAllX509TrustManager")
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
    
                @SuppressLint("TrustAllX509TrustManager")
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }
            };
            SSLContext sc = SSLContext.getInstance("SSL"); // Add in try catch block if you get error.
            sc.init(null, trustAllCerts, new java.security.SecureRandom()); // Add in try catch block if you get error.
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    
            HostnameVerifier usnoHostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
    
            SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
    
            connection = (HttpsURLConnection) urlDownload.openConnection();
            connection.setHostnameVerifier(usnoHostnameVerifier);
            connection.setSSLSocketFactory(sslSocketFactory);
    
            return connection;
        }
    

提交回复
热议问题