2012-03-24 48 views
2

有几个问题讨论如何使用multipart/form-data数据格式将进度指示添加到Android中的HTTP文件上传中。建议的典型方法在Can't grab progress on http POST file upload (Android)的顶部答案中有所体现 - 从完整的Apache HTTPClient库中包含MultipartEntity类,然后将其用于获取数据的输入流包装为一个读取字节数的输入流。UrlEncodedFormEntity的Android HTTP上传进度

这种方法适用于这种情况,但不幸的是,它不适用于通过UrlEncodedFormEntity发送数据的请求,该请求需要将其数据传递给Strings而不是InputStreams。

所以我的问题是,有什么办法可以通过这种机制来确定上传进度?

回答

5

您可以覆盖任何HttpEntity实现的#writeTo方法,并在写入输出流时计数字节。

DefaultHttpClient httpclient = new DefaultHttpClient(); 
try { 
    HttpPost httppost = new HttpPost("http://www.google.com/sorry"); 

    MultipartEntity outentity = new MultipartEntity() { 

    @Override 
    public void writeTo(final OutputStream outstream) throws IOException { 
     super.writeTo(new CoutingOutputStream(outstream)); 
    } 

    }; 
    outentity.addPart("stuff", new StringBody("Stuff")); 
    httppost.setEntity(outentity); 

    HttpResponse rsp = httpclient.execute(httppost); 
    HttpEntity inentity = rsp.getEntity(); 
    EntityUtils.consume(inentity); 
} finally { 
    httpclient.getConnectionManager().shutdown(); 
} 

static class CoutingOutputStream extends FilterOutputStream { 

    CoutingOutputStream(final OutputStream out) { 
     super(out); 
    } 

    @Override 
    public void write(int b) throws IOException { 
     out.write(b); 
     System.out.println("Written 1 byte"); 
    } 

    @Override 
    public void write(byte[] b) throws IOException { 
     out.write(b); 
     System.out.println("Written " + b.length + " bytes"); 
    } 

    @Override 
    public void write(byte[] b, int off, int len) throws IOException { 
     out.write(b, off, len); 
     System.out.println("Written " + len + " bytes"); 
    } 

}