2012-07-25 37 views
7

Trong ứng dụng Android của tôi, tôi đang cố gắng lấy dữ liệu từ máy chủ bằng cách thực hiện yêu cầu POST.getHttpResponseCode() trả về -1 trong android 2.2

Tôi đang sử dụng HttpURLConnection lớp để thực hiện các yêu cầu như Apache HttpClient không còn được duy trì bởi Android.

Đây là những gì tôi đang làm.

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; 
} 

Tính năng này hoạt động tốt trên mọi thiết bị ngoại trừ thiết bị chạy 2.2 (không thử trên 2.1).

Trong 2.2, nó hoạt động tốt. Nhưng nếu tôi để lại phần này của mã nhàn rỗi trong hơn 30 giây, nó trả về tôi với -1 là mã phản hồi http trong lần tiếp theo.

Một điều cần lưu ý khác là điều này chỉ xảy ra với url HTTPS chứ không phải với Url HTTP. Tôi không muốn sử dụng lớp HttpsURLConnection bởi vì đôi khi tôi có thể muốn sử dụng http là tốt.

Tôi không đóng kết nối chỉ để giữ kết nối luôn hoạt động. Tôi đang làm gì sai?

+0

các kết nối Https tự động đóng sau một khoảng thời gian nhất định (Nếu không có gì được chuyển ý tôi)? Tôi không thực sự biết nhiều về kết nối https vì vậy điều này có thể hoàn toàn sai. (Đọc nó trở lại Tôi thậm chí không chắc chắn những gì tôi nói có ý nghĩa lol) –

+0

-1 thường là khi một kết nối không thành công vì một lý do không được chỉ định bởi mã HTTP - trong trường hợp của bạn nó có vẻ như một thời gian chờ nhưng nó cũng có thể là sự thất bại về độ phân giải DNS, v.v ... Bây giờ, khi _why_ một phiên bản cụ thể của Android đã hết thời gian, tôi không biết ... – Basic

+0

Ý tưởng của tôi là nếu tôi không làm gì sai, thì vấn đề này chỉ với tôi? Bởi vì tìm kiếm trên web, tôi thấy không có ai gặp vấn đề này. – Enigma

Trả lời

0

Nếu bạn muốn sử dụng Https và Http cùng một lúc và không muốn tạo ra một kết nối riêng biệt -Và nếu HttpsUrlConnection giải quyết "-1 vấn đề" của bạn bạn có thể sử dụng phương pháp sau đây:

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

Tôi đã trả lời this làm tham chiếu

Các vấn đề liên quan