Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 678
x2on Avatar asked Apr 08 '14 09:04

x2on


1 Answers

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

like image 98
x2on Avatar answered Nov 12 '22 15:11

x2on