Adding SSL Certificate to Retrofit 2

I assume that you already know how to get SSL certificate from your server and you already put it in android resource inside “raw” directory.

SSL Certificate File

Here is how to read in in android and add to your retrofit.

private static SSLContext getSSLConfig(Context context) throws CertificateException, IOException,
            KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    // Loading CAs from an InputStream
    CertificateFactory cf = null;
    cf = CertificateFactory.getInstance("X.509");

    Certificate ca;
    // I'm using Java7. If you used Java6 close it manually with finally.
    try (InputStream cert = context.getResources().openRawResource(R.raw.your_certificate)) {
        ca = cf.generateCertificate(cert);

    // Creating a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore   = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Creating a TrustManager that trusts the CAs in our KeyStore.
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);

    // Creating an SSLSocketFactory that uses our TrustManager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    return sslContext;

By default Retrofit using OkHttp as the http client library, and here is the last step.

Retrofit.Builder builder = new Retrofit.Builder().baseUrl(Constant.BASE_API_URL);

OkHttpClient okHttp = new OkHttpClient();

Retrofit retrofit = builder.client(okHttp).build();