UrlEncodedFormEntity 的 Android HTTP 上传进度

标签 android httpclient

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

此方法适用于这种情况,但遗憾的是不适用于通过 UrlEncodedFormEntity 发送数据的请求,该请求希望其数据以字符串而不是 InputStream 的形式传递给它。

所以我的问题是,有哪些方法可以通过此机制确定上传进度?

最佳答案

您可以重写任何 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");
    }

}

关于UrlEncodedFormEntity 的 Android HTTP 上传进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9854555/

相关文章:

android - 在 Genymotion 的实时数据库上打开 Realm 浏览器?

android - java.lang.IllegalArgumentException : width and height must be > 0 when setting bitmap 异常

c++ - proxygen 中的 http 客户端?

Android webservice GET 请求只回复部分 XML 响应

android - 应用程序服务器如何将 Google 帐户关联到用户的设备?

android - (a) 击打 : TLS socket is closed when trying to login with XMPP

android studio 模拟器在 3.0 更新后崩溃

tomcat - Tomcat 6 中的 sun.net.www.http.HttpClient 内存泄漏

httpclient - zuul 代理缓慢 - RibbonLoadBalancingHttpClient

c# - HttpClient 响应没有得到刷新