x2on
x2on

Reputation: 2297

HttpClient Post with progress and MultipartEntityBuilder

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...

Upvotes: 7

Views: 10739

Answers (1)

x2on
x2on

Reputation: 2297

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

Upvotes: 17

Related Questions