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

时间:2011-03-14 03:49:54

标签: 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();
  }
}

我只是想知道如何获得上传的字节总和?

1 个答案:

答案 0 :(得分:4)

覆盖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,并在上传期间或帖子完成后检索字节数。