监视输入流/ httpclient.execute的进度

时间:2011-03-02 02:05:15

标签: java android

我正在尝试获取Apache HTTP Client Execute方法的进度。是否有可能

  1. 获取execute方法读取的输入流的挂载 或
  2. 使用某种内部方法监控执行过程的百分比或发送的数据量?
  3. 下面的代码将输入流发送到服务器(在这种情况下是图像),然后将其妥善存储。问题在于高分辨率相机和慢速移动运营商很难判断上传是否真的发生了。代码确实有效,但需要反馈。

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

1 个答案:

答案 0 :(得分:2)

我更喜欢稍微“装饰”流/读取器/编写器对象,将所需的进度功能添加到其中。在装饰流/读/写器中,您可以保留一个计数器来指示进度,甚至可以将指示器回调到其中。 ; - )

这样的事情:

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

实际上,整个Java IO包都很好地展示了这种设计模式。