开发者

Android SSL error: certificate not trusted...sometimes

开发者 https://www.devze.com 2023-02-20 16:36 出处:网络
In the app I\'m working on, I have to make an HTTPS connection to a web server.I was getting certificate not trusted errors and after consulting stackoverflow, I found this blog posting:

In the app I'm working on, I have to make an HTTPS connection to a web server. I was getting certificate not trusted errors and after consulting stackoverflow, I found this blog posting: http://blog.antoine.li/index.php/2010/10/android-trusting-ssl-certificates/

It seems like the CA for this server is not included in Android's default store. In a nutshell, I downloaded all the certificates, created a keystore with the BKS provider, imported the keys, imported the keystore int开发者_Go百科o my project, subclassed the DefaultHttpClient class to force it to use my keystore.

After following the steps in the blog, it worked perfectly on the emulator. However, when I test it on a device, it fails intermittently. I think I've isolated a pattern. It seems like after some time has passed and I try to make an HTTPS connection, it will fail. Then, if I attempt the same connection again, it will succeed. If I wait a while and then try again, it fails the first time, succeeds on repeated attempts. I can probably fix it by just making multiple attempts on failure, but I would like to know what is going on. The behavior suggests some kind of cache but I don't know how to go about finding it or modifying its behavior. Does anyone have any suggestions about what is going on or know what I'm doing wrong? Any help would be appreciated.


I solved a similar problem by setting

System.setProperty("http.keepAlive", "false");

before I did my HTTP calls. There seems to be a problem with Android keep closed connections in its connection pool and trying to reuse them.


You can "skip" the certificates. Yes, you'll lose security but sometimes it's the only solution...

To do it. First, declare a TrustManager:

    private TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager()
    {
        public java.security.cert.X509Certificate[] getAcceptedIssuers()
        {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
        {

        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
        {

        }
    }
};

Second, change the SSL Context:

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

I hope help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号