java - HttpClient 上传大文件并显示发送的字节数

标签 java http

我找到了这个代码示例

import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

我只是想知道如何获取上传的字节数?

最佳答案

覆盖 FileBody.writeTo(OutputStream) 以在写入字节时对其进行计数。这允许在上传期间和完成后计算发送的字节数(即使中断)。

public class FileBodyCounter extends FileBody {
    private volatile long byteCount;

    public long getBytesWritten() {
        return byteCount;
    }

    public void writeTo(OutputStream out) {
        super.writeTo(new FilterOutputStream(out) {
            // Other write() methods omitted for brevity. Implement for better performance
            public void write(int b) throws IOException {
                byteCount++;
                super.write(b);
            }
        });
    }
}

使用它代替标准的 FileBody,并在上传期间或发布完成后检索字节数。

关于java - HttpClient 上传大文件并显示发送的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5294532/

相关文章:

java - 如何正确读取http请求?

java - 定位 S+(版本 31 及更高版本)需要 FLAG_IMMUTABLE 或 FLAG_MUTABLE 之一

java - 将 JAR 文件转换为可执行文件是否可以确保其分发?

php - $http header 不是函数 - angularjs

security - 一次性csrf token的优点

php - 使用php将数据从android发送到mysql

java - jasperReport 文件出错

java - 如何在 keyPressed(KeyEvent e) 方法中添加击键来更改球的颜色?简单的 KeyListener 演示

java - Java SDK 的 Couchbase 连接超时

c# - Azure CDN 端点使用 https 提供 502 错误网关