trusting all certificates using http client over https SSL - Android Network

Android examples for Network:HTTP

Description

trusting all certificates using http client over https SSL

Demo Code


import android.content.Context;
import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class Main{
    /** See http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/16022833#16022833
     * for information on how to get the certificate file
     *///w  w w .j  a v  a2s. co  m
    public static void trustGeotrustCertificate(final Context context)
            throws GeneralSecurityException, IOException {
        final KeyStore trustStore = KeyStore.getInstance("BKS");
        final InputStream in = context.getResources().openRawResource(
                R.raw.geotrust_cert);
        trustStore.load(in, null);

        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        final SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(null, tmf.getTrustManagers(),
                new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx
                .getSocketFactory());
    }
}

Related Tutorials