Accept Self-Signed Certificate – Java Android – HttpsUrlConnection

Just paste the code below into your app, to obtain the file you need to assign to “certName”, use Firefox:

    • Browse the site which is using that specific certificate
    • Click the padlock/More/Security/View Certificate/Details/Export
    • Save the file as certName (type X.509 Certificate (PEM))
private static void validateSSLCertificateFromAssets(Context appContext, String certName) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = new BufferedInputStream(appContext.getAssets().open(certName));
    Certificate ca = cf.generateCertificate(caInput);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(sslFactory);
}

Enjoy!