2011-03-02 40 views
2

我正在嘗試獲取Apache HTTP客戶端執行方法的進度。是否有可能要麼監視輸入流/ httpclient.exectute的進度

  1. 獲取輸入流的安裝已讀通過一些內部方法或者通過百分比或數據量的執行方法 或
  2. 監控執行過程中發送?

下面的代碼發送一個輸入流到服務器(在這種情況下是一個圖像),然後適當地存儲。問題在於高分辨率照相機和慢速移動運營商很難判斷上傳是否真正發生。代碼確實有用,但需要反饋。

public List writeBinary(String script, InputStream lInputStream) { 
     Log.d(Global.TAG,"-->writing to server..."); 

     HttpParams httpParameters = new BasicHttpParams(); 
     HttpConnectionParams.setConnectionTimeout(httpParameters, 5*1000); 
     HttpConnectionParams.setSoTimeout(httpParameters, 60*1000); 

     HttpClient httpclient = new DefaultHttpClient(httpParameters); 
     HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx" + script); 

     String responseText = null; 
     List responseArray = new ArrayList(); 

     try { 
      httppost.setEntity(new InputStreamEntity(lInputStream, -1)); 
      HttpResponse response = httpclient.execute(httppost); 

      if (response.getStatusLine().getStatusCode() == 200){ 
       InputStream lInputStreamResponse = response.getEntity().getContent(); 
       DataInputStream lDataInputStream = new DataInputStream(lInputStreamResponse); 
       BufferedReader lBufferReader = new BufferedReader(new InputStreamReader(lDataInputStream)); 

       while ((responseText = lBufferReader.readLine()) != null){ 
        responseArray.add(responseText); 
       } 

       lInputStream.close(); 
      } 

     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return responseArray; 
    } 

回答

2

我更喜歡「裝飾」流/讀者/寫者對象一點點,添加所需的進度功能。在裝飾流/讀寫器中,您可以保留一個計數器來指示進度,甚至可以將指標回調放入其中。 ;-)

事情是這樣的:

public Class CountableOutputStream implements OutputStream { 
    private int counter; 
    private OutputStream origStream; 
    ...... 
} 

事實上,整個的Java IO包演示這種設計模式相當好。