Skip to content

Instantly share code, notes, and snippets.

@IgorGanapolsky
Created October 23, 2015 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IgorGanapolsky/e644522a4c8441dc9db6 to your computer and use it in GitHub Desktop.
Save IgorGanapolsky/e644522a4c8441dc9db6 to your computer and use it in GitHub Desktop.
OkHttpClient
/**
* Provides a Retrofit client that uses OkHttp for communication.
*
* @return {@link OkHttpClient}.
*/
@Provides
@Singleton
OkHttpClient provideApiClient(AuthenticationInterceptor authenticationInterceptor) {
OkHttpClient client = new OkHttpClient();
client.interceptors().add(authenticationInterceptor);
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("TLSv1");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client.setSslSocketFactory(sslSocketFactory);
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return client;
}
@rajuashok
Copy link

Did this ever work for you? I'm getting "Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found."

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