Skip to content

Instantly share code, notes, and snippets.

@mefarazath
Forked from chalup/GagSsl.java
Last active June 1, 2022 16:07
Show Gist options
  • Save mefarazath/c9b588044d6bffd26aac3c520660bf40 to your computer and use it in GitHub Desktop.
Save mefarazath/c9b588044d6bffd26aac3c520660bf40 to your computer and use it in GitHub Desktop.
Get OkHttpClient which ignores all SSL 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);
}
}
@iamakg
Copy link

iamakg commented Jun 2, 2017

Thanks, this is awesome.

@geoandri
Copy link

Thanks for this!

@dj-4war
Copy link

dj-4war commented Aug 20, 2017

public static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConstants.PING_URL)
.client(getUnsafeOkHttpClient())
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
}

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 java.security.cert.X509Certificate[0];
                    }
                }
        };

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                Log.d("TAG", "Trust Host :" + hostname);
                return true;
            }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        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(hostnameVerifier).build();



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

I am still getting the hand shake exception.

On 5.0+ devices I am getting hand shake error. I tried all the ways suggested over the Web but no use Please help ASAP.
Connection closed by peer
08-20 21:07:15.587 31640-8149/com.we.samples W/System.err: javax.net.ssl.SSLHandshakeException: Connection closed by peer
08-20 21:07:15.588 31640-8149/com.we.samples W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
08-20 21:07:15.588 31640-8149/com.we.samples W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357)
08-20 21:07:15.588 31640-8149/com.we.samples W/System.err: at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:281)
08-20 21:07:15.588 31640-8149/com.we.samples W/System.err: at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:251)
08-20 21:07:15.589 31640-8149/com.we.samples W/System.err: at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:151)
08-20 21:07:15.589 31640-8149/com.we.samples W/System.err: at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:195)
08-20 21:07:15.589 31640-8149/com.we.samples W/System.err: at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
08-20 21:07:15.589 31640-8149/com.we.samples W/System.err: at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
08-20 21:07:15.589 31640-8149/W/System.err: at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
08-20 21:07:15.589 31640-8149/W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
08-20 21:07:15.590 31640-8149/ W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
08-20 21:07:15.590 31640-8149 W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
08-20 21:07:15.590 31640-8149/W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
08-20 21:07:15.590 31640-8149/ W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
08-20 21:07:15.590 31640-8149/ W/System.err: at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
08-20 21:07:15.590 31640-8149/ W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
08-20 21:07:15.591 31640-8149/ W/System.err: at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
08-20 21:07:15.591 31640-8149/com.we.samples W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
08-20 21:07:15.591 31640-8149/com.we.samples W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
08-20 21:07:15.591 31640-8149/com.we.samples W/System.err: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
08-20 21:07:15.591 31640-8149/com.we.samples W/System.err: at okhttp3.RealCall.execute(RealCall.java:69)
08-20 21:07:15.591 31640-8149/com.we.samples W/System.err: at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
08-20 21:07:15.591 31640-8149/com.we.samples W/System.err: at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91)

@ThomasEA
Copy link

Hi @dj-4war! How did you resolve the issues "Connection closed by peer" for Android 5.0+?

@flasher297
Copy link

flasher297 commented Feb 8, 2018

What's a difference between this approach and standard Okhttp builder methods?

 final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
                .sslSocketFactory(SslMockUtils.TRUST_ALL_SOCKET_FACTORY, SslMockUtils.TRUST_MANAGER)
                .hostnameVerifier(SslMockUtils.TRUST_ALL_HOSTNAME_VERIFIER);

@AlexandrMishin
Copy link

What's a difference between this approach and standard Okhttp builder methods?

 final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
                .sslSocketFactory(SslMockUtils.TRUST_ALL_SOCKET_FACTORY, SslMockUtils.TRUST_MANAGER)
                .hostnameVerifier(SslMockUtils.TRUST_ALL_HOSTNAME_VERIFIER);

SslMockUtils is Not standart for OkHttpClient . Maybe this Utils have same realisation

@UnHumbleBen
Copy link

UnHumbleBen commented Jun 24, 2020

Is there a way to write this in version okhttp 2.7.5? OkHttpClient does not have a Builder in that version.

I replaced the return statement with these lines:

            OkHttpClient client = new OkHttpClient();
            client.setSocketFactory(sslSocketFactory);
            client.setHostnameVerifier(
                    new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    }
            );
            return client;

It seems like OkHttpClient does not have aX509TrustManager field in version 2.7.5, so I omitted it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment