我正在尝试在 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());