Trusting all certificates using HttpClient over HTTPS?

Add this code before the HttpsURLConnection and it will be done.

private void trustEveryone() { 

    try { 

            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){ 

                    public boolean verify(String hostname, SSLSession session) { 

                            return true; 


            SSLContext context = SSLContext.getInstance("TLS"); 

            context.init(null, new X509TrustManager[]{new X509TrustManager(){ 

                    public void checkClientTrusted(X509Certificate[] chain, 

                                    String authType) throws CertificateException {} 

                    public void checkServerTrusted(X509Certificate[] chain, 

                                    String authType) throws CertificateException {} 

                    public X509Certificate[] getAcceptedIssuers() { 

                            return new X509Certificate[0]; 

                    }}}, new SecureRandom()); 



    } catch (Exception e) { // should never happen 



You basically have four potential solutions to fix a "Not Trusted" exception on Android using httpclient:


Trust all certificates. Don't do this, unless you really know what you're doing.

Create a custom SSLSocketFactory that trusts only your certificate. This works as long as you know exactly which servers you're going to connect to, but as soon as you need to connect to a new server with a different SSL certificate, you'll need to update your app.

Create a keystore file that contains Android's "master list" of certificates, then add your own. If any of those certs expire down the road, you are responsible for updating them in your app. I can't think of a reason to do this.

Create a custom SSLSocketFactory that uses the built-in certificate KeyStore, but falls back on an alternate KeyStore for anything that fails to verify with the default.