[Android] HttpsURLConnection.getResponseCode = -1

[Android] HttpsURLConnection.getResponseCode = -1

Recently I used below code to implement my app to connect server using HttpsURLConnection, I can connect to the web service with inputted username and password, and get a response back, however I found sometimes the android 2.2 device will throw “org.xml.sax.SAXParseException: Unexpected end of document” error message in logcat.

InputStream is = null;

try {
  SSLContext context2 = SSLContext.getInstance("TLS");
  context2.init(
    null, new X509TrustManager[]{
      new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}
        public X509Certificate[] getAcceptedIssuers() {
          return new X509Certificate[0];
        }
      }
    }, new SecureRandom()
  );

  HttpsURLConnection.setDefaultSSLSocketFactory(context2.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    }
  );

  HttpsURLConnection conn = (HttpsURLConnection) new URL(Url).openConnection();
  conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("Connection", "Keep-Alive");
  conn.setRequestProperty("Charset", "UTF-8");
  conn.setFixedLengthStreamingMode(params.getBytes().length);
  conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  PrintWriter out = new PrintWriter(conn.getOutputStream());
  out.print(params);
  out.close();
  is = conn.getInputStream();
} catch (Exception e) { // should never happen
  e.printStackTrace();
}

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
NodeList nList;
Document doc;
db = dbf.newDocumentBuilder();
if (is != null) {
  doc = db.parse(is);//throw org.xml.sax.SAXParseException 
  if (doc.hasChildNodes()) {
    doc.getDocumentElement().normalize();
    nList = doc.getElementsByTagName("ax21:exception");
    exception = (nList.item(0).getFirstChild() != null) ? nList.item(0).getFirstChild().getNodeValue() : "";
    nList = doc.getElementsByTagName("ax21:logincode");
    logincode = (nList.item(0).getFirstChild() != null) ? nList.item(0).getFirstChild().getNodeValue() : "";
    ...
    ...
    ...
  }
}

I traced my codes, and found in unknown situation use HttpsURLConnection will return null InputStream, it caused DocumentBuilder parser InputStream failed.

But why HttpsURLConnection can be used in android 2.3.X device normally, but in android 2.2.X device unsuccessfully?I kept on traced codes step by step, I found when throw org.xml.sax.SAXParseException: Unexpected end of document” , HttpsURLConnection.getReponseCode is -1(in normal case will return 200), and I can’t get anything back. But I am very sure the server is working well, and internet connection is good too, why HttpsURLConnection.getReponseCode is -1??

Finally I found answer in this link:
http://android-developers.blogspot.tw/2011/09/androids-http-clients.html

You should add “System.setProperty(“http.keepAlive”, “false”);” in your code before you do HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

And my app works successful with no exception.

(Visited 36 time, 1 visit today)
Facebooktwittergoogle_plusredditpinterestlinkedinmail
Comments are closed.