HttpClient upload big file and show sent bytes num

2019-02-23 22:06发布

问题:

I have found this code sample

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

I am just wondering how to get uploaded bytes sum?

回答1:

Override FileBody.writeTo(OutputStream) to counts bytes as they are written. This allows a count of bytes sent (even if interrupted), both during the upload and after it is complete.

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

Use that instead of the standard FileBody, and retrieve the bytecount during upload, or after the post has completed.



标签: java http