2012-07-25 70 views
7

在我的android应用程序中,我试图通过执行POST请求从服务器获取数据。getHttpResponseCode()在android 2.2中返回-1

我使用HttpURLConnection类来提出请求,因为Apache的HttpClient不再由android维护。

这是我正在做的。

private boolean callWS() { 
    try { 

     // To avoid the bug in httpurlconnection prior froyo which 
     // causes the getInputStream to return headers along with response 
     if (Build.VERSION.SDK_INT < 8) 
      System.setProperty("http.keepAlive", "false"); 

     mHttpResponseCode = 0; 
     mErrorMessage = ""; 

     // Initialize connection 
     URL connectURL = new URL(mServerUrl); 

     HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection(); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 
     conn.setUseCaches(false); 
     conn.setInstanceFollowRedirects(true); 
     conn.setReadTimeout(30000); 
     conn.setConnectTimeout(15000); 
     conn.setRequestMethod("POST"); 

     // Set some headers 
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     connection.setRequestProperty("Accept-Encoding", "deflate, gzip"); 
     connection.setRequestProperty("Content-Length", mParameters.length() + ""); 

     // Connect to host 
     conn.connect(); 

     // Write parameters to connection 
     OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); 
     writer.write(mParameters); 
     writer.flush(); 
     writer.close(); 

     // Wait for http response code 
     mHttpResponseCode = conn.getResponseCode(); 

     // Read response from connection 
     BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
     ByteArrayBuffer baf = new ByteArrayBuffer(50); 
     int read = 0; 
     int bufSize = 1024; 
     byte[] buffer = new byte[bufSize]; 

     while (true) { 
      read = bis.read(buffer); 
      if (read == -1) 
       break; 
      baf.append(buffer, 0, read); 
     } 

     // Decompress gzipped response 
     if (conn.getHeaderField("Content-Encoding") != null && conn.getHeaderField("Content-Encoding").contains("gzip")) 
      mResponseString = decompress(baf.toByteArray()); 
     else 
      mResponseString = new String(baf.toByteArray()); 

     mResponse.setResponse(mResponseString);   
     isWSCallSuccessfull = true; 
    } catch(UnknownHostException unknownHostException) { 
     isWSCallSuccessfull = false; 
     mErrorMessage = "Unknown host exception"; 
     unknownHostException.printStackTrace(); 
     mLogger.putStacktrace(unknownHostException); 
    } catch(SocketException socketException) { 
     isWSCallSuccessfull = false; 
     mErrorMessage = "Socket Exception"; 
     socketException.printStackTrace(); 
     mLogger.putStacktrace(socketException); 
    } catch(SocketTimeoutException socketTimeOutException) { 
     isWSCallSuccessfull = false; 
     mErrorMessage = "Socket Timeout Exception"; 
     socketTimeOutException.printStackTrace(); 
     mLogger.putStacktrace(socketTimeOutException); 
    } catch(SSLException sslException) { 
     isWSCallSuccessfull = false; 
     mErrorMessage = "SSL Exception"; 
     sslException.printStackTrace(); 
     mLogger.putStacktrace(sslException); 
    } catch(IOException ioException) { 
     isWSCallSuccessfull = false; 
     mErrorMessage = "IO Exception " + ioException.getMessage(); 
     ioException.printStackTrace(); 
     mLogger.putStacktrace(ioException); 
    } 

    mResponse.setHttpResponseCode(mHttpResponseCode); 
    mResponse.setErrorMessage(mErrorMessage); 
    mResponse.isWSCallSuccessful(isWSCallSuccessfull); 

    return isWSCallSuccessfull; 
} 

这工作正常,除了设备运行2.2(没有在2.1上试用它)的设备。

在2.2中,它工作正常。但是,如果我将这部分代码闲置超过30秒,它将在下一次返回-1作为http响应代码。

另一件需要注意的事情是,这只会发生在HTTPS网址上,而不会发生在HTTP网址上。我不想使用HttpsURLConnection类,因为有时我可能也想使用http。

我不关闭连接只是为了保持连接活着。我究竟做错了什么?

+0

做一段时间后Https连接会自动关闭(如果没有任何东西正在传输,我的意思是)?我对https连接不太了解,所以这可能是完全错误的。 (读回来,我甚至不知道我说的话有道理lol) – 2012-07-25 11:29:11

+0

-1通常当连接失败的原因不是由HTTP代码指定的 - 在你的情况下,它听起来像一个超时,但它也可能是DNS解析失败等...现在,为什么_why_特定版本的Android是超时,我不知道... – Basic 2012-07-25 13:59:23

+0

嗯,我的想法是,如果我没有做错什么,那么这个问题只是跟我?由于在网上搜索,我发现没有人有这个问题。 – Enigma 2012-07-25 14:01:56

回答

0

如果你想使用HTTPS和HTTP的同时,不希望创建一个单独的连接-and如果HttpsUrlConnection解决您“-1号”你可以用下面的办法:

URLConnection conn = new URL(url).openConnection(); 
if (conn instanceof HttpsURLConnection) { 
    // do stuff with cast to HttpsUrlConection 
} 
else { 
    // do stuff with cast to HttpUrlConnection 
} 

我把this答案作为参考