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.