Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore SSL error in Okhttp? [duplicate]

I've Installed and turned the PacketCapture on, then When I request an API using Okhttp to my server, I get this exception.

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

Is it possible to ignore SSL errors?

like image 753
Steph Jayden Avatar asked Jun 21 '18 05:06

Steph Jayden


1 Answers

OkHttpClient.Builder allows you to add your own SSLContext and TrustManager. Here is the code from this gist which ignore all errors:

private static OkHttpClient 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 X509Certificate[0];
                    }
                }
        };

        // 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();

        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                }).build();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Note: This is an unsafe solution. Use it for debugging stuff.

like image 199
Saeed Masoumi Avatar answered Oct 15 '22 22:10

Saeed Masoumi