在android2.2上HttpsURLConnection奇怪的行为

时间:2011-11-01 19:22:03

标签: android ssl-certificate http-status-codes httpurlconnection httpconnection

我正在尝试在android中打开https连接。当我在android 3或1.6中运行下面的代码时,一切都像魅力一样。但在android 2.2中,它有时会给我-1连接响应。
Android 2.2:
连接尝试给出-1响应代码
睡200毫秒
连接尝试给出-1响应代码
睡200毫秒
连接尝试给出http200

另一项审判 连接尝试给出-1响应代码
睡200毫秒
连接尝试给出http200

我的问题是如何在Android 2.2中克服这种chaning响应。我甚至不知道在哪里看。如果有人可以指导我朝着正确的方向前进,我会很高兴。

这是代码:

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());

2 个答案:

答案 0 :(得分:3)

尝试禁用keep alive,如果这没有用,请尝试禁用缓存:

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

更多信息is in this thread

答案 1 :(得分:2)

HttpURLConnection在2.3

之前有一些错误

建议使用Apache HttpClient for 2.2及更早版本。和HttlURLConnection for 2.3及以后。

有关详情,请参阅此Developer Blog post