6

I try to implement an progress while uploading an file with HttpClient 4.3.3 and MultipartEntityBuilder

So actually i execute a post request with the following code

HttpClientBuilder builder = HttpClientBuilder.create();
HttpClient httpClient = builder.build();

HttpPost httpPost = new HttpPost(uploadUrl);

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addPart("filea", new FileBody(filea));
entityBuilder.addPart("fileb", new FileBody(fileb));

final HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(httpPost);

Any idea how to get the actual progress from the upload? I searched a lot - but the examples are for android and not plain java or an older version of HttpClient and didn't work for me...

x2on
  • 2,267
  • 3
  • 24
  • 44

1 Answers1

15

I just found a solution for that:

You need an HttpEntityWrapper which counts the processed bytes and has a callback.

ProgressHttpEntityWrapper.ProgressCallback progressCallback = new ProgressHttpEntityWrapper.ProgressCallback() {

        @Override
        public void progress(float progress) {
            //Use the progress
        }

    }

httpPost.setEntity(new ProgressHttpEntityWrapper(entityBuilder.build(), progressCallback));

And here is the complete code from the ProgressHttpEntityWrapper: https://github.com/x2on/gradle-hockeyapp-plugin/blob/master/src/main/groovy/de/felixschulze/gradle/util/ProgressHttpEntityWrapper.groovy

Main source for this solution: https://stackoverflow.com/a/7319110/268795

Community
  • 1
  • 1
x2on
  • 2,267
  • 3
  • 24
  • 44
  • Hi, I have used your solution for calculating uploaded file size and remaining file size but it differ from actual file size present in gallery. Do you have any idea? why the file size gets vary? – Sangeetha Aug 08 '16 at 07:24
  • There is a delay between ProgressCallback reporting 100% creation and the HttpServer actually responding status ok, what accounts for the diference – Paul Taylor Jul 07 '17 at 13:28