2

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

另一个试用
连接尝试给出-1响应代码
睡眠200毫秒
连接尝试给出http200

我的问题是我该如何克服android 2.2 中的这种变化响应。我什至不知道在哪里看。如果有人可以指导我正确的方向,我会很高兴。

这是代码:

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

2 回答 2

3

尝试禁用保持活动,如果这没有帮助,请尝试禁用缓存:

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

更多信息在这个线程中。

于 2011-11-01T20:28:13.123 回答
2

HttpURLConnection 在 2.3 之前有一些 bug

对于 2.2 及更早版本,建议使用 Apache HttpClient。和 2.3 及更高版本的 HttlURLConnection。

有关更多信息,请参阅此开发人员博客文章

于 2011-11-01T20:35:26.250 回答