2011-11-03 75 views
3

根據設置,我通過HttpsUrlConnectionHttpUrlConnection從我的Android應用程序連接到Web服務器。目前我沒有任何問題,但昨天我開始得到http/https status回覆-1。即使存在某種錯誤,Web服務器也無法將此返回給我。我連接的服務器旨在在出現某種問題時返回errorCodeerrorString。這是我正在使用的代碼,但我不認爲問題在這裏。Android Https狀態碼-1

public void UseHttpConnection(String url, String charset, String query) { 
    try { 
     HttpURLConnection connection = (HttpURLConnection) new URL(url) 
       .openConnection(); 
     connection.setDoOutput(true); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Charset", charset); 
     connection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded;charset=" + charset); 
     OutputStream output = null; 
     try { 
      output = connection.getOutputStream(); 
      output.write(query.getBytes(charset)); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (output != null) 
       try { 
        output.close(); 
       } catch (IOException logOrIgnore) { 
       } 
     } 

     int status = ((HttpURLConnection) connection).getResponseCode(); 
     Log.i("", "Status : " + status); 

     for (Entry<String, List<String>> header : connection 
       .getHeaderFields().entrySet()) { 
      Log.i("Headers", 
        "Headers : " + header.getKey() + "=" 
          + header.getValue()); 
     } 

     InputStream response = new BufferedInputStream(
       connection.getInputStream()); 

     int bytesRead = -1; 
     byte[] buffer = new byte[30 * 1024]; 
     while ((bytesRead = response.read(buffer)) > 0) { 
      byte[] buffer2 = new byte[bytesRead]; 
      System.arraycopy(buffer, 0, buffer2, 0, bytesRead); 
      handleDataFromSync(buffer2); 
     } 
     connection.disconnect(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

所以我的問題是,-1應該代表什麼。它是對某種錯誤還是其他的反應?

回答

4

HTTP響應代碼-1表示連接或響應處理出錯。 HttpURLConnection在保持連接的情況下經常出現故障。

如果您想關閉該功能,則必須將http.keepAlive系統屬性設置爲false。

以編程方式做到這一點的方法是把這個在你的應用程序的開頭:

System.setProperty("http.keepAlive", "false"); 
+1

其實我認爲它解決了我的問題。最起碼到現在。 –

+0

我希望這會繼續爲你工作。祝你好運! – Manu

+1

雖然這並不適用於我! – Enigma