简体   繁体   中英

HttpsURLConnection strange behaviour on android2.2

I am trying to open a https connection in android. When i run the code below in android 3 or 1.6 everything works like a charm. But in android 2.2 sometimes it gives me -1 connection response.
Android 2.2 :
connection attemp gives -1 response code
sleep 200 miliseconds
connection attemp gives -1 response code
sleep 200 miliseconds
connection attemp gives http200

Another trial
connection attemp gives -1 response code
sleep 200 miliseconds
connection attemp gives http200

My question is how can i overcome this chaning response in android 2.2. I dont even know where to look. I will appriciate if someone can guide me in the right direction.

Here is the code:

HttpsURLConnection con;
    URL adress = new URL("https:\\www.url.com/service.asp?someparam");
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
    } };
    try {
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
            sc = SSLContext.getInstance("TLS");
        }
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
    con = (HttpsURLConnection) adress.openConnection();
    ((HttpsURLConnection) con).setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    Log.d("response code", "" + con.getResponseCode());

Try to disable keep alive and if this doesn't help, try to disable caching:

System.setProperty("http.keepAlive", "false");
con = (HttpsURLConnection) adress.openConnection();
con.setUseCaches(false);

More information is in this thread .

HttpURLConnection has some bugs before 2.3

It is recommended to use Apache HttpClient for 2.2 and earlier. and HttlURLConnection for 2.3 and onwards.

see this Developer Blog post for more information on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM