Skip to content

Instantly share code, notes, and snippets.

@chalup
Created January 30, 2014 11:30
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save chalup/8706740 to your computer and use it in GitHub Desktop.
Save chalup/8706740 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 null;
}
}
};
// 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 okHttpClient = new OkHttpClient();
okHttpClient.setSslSocketFactory(sslSocketFactory);
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@tomascrespo
Copy link

tomascrespo commented Mar 30, 2021

I have this error.

java.lang.RuntimeException: java.lang.IllegalStateException: trustManager.acceptedIssuers must not be null
at com.example.advertiseapp.API_Package.RetrofitClientBase.getUnsafeOkHttpClient(RetrofitClientBase.java:103)
...

Replace
@Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }

With
@Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; }

@dineshr93
Copy link

Hi @chalup Can u license your code to Apache 2.0 same as okhttp library?

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