具有进度和MultipartEntityBuilder的HttpClient发布(HttpClient Post with progress and MultipartEntityBuilder)

问题

我尝试在使用HttpClient 4.3.3和MultipartEntityBuilder上传文件时实现进度

所以实际上我用以下代码执行发布请求

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

知道如何从上传中获取实际进度吗? 我进行了很多搜索-但示例仅针对android系统,而不是纯java或HttpClient的旧版本,因此对我不起作用...

回答1

我刚刚找到了一个解决方案:

您需要一个HttpEntityWrapper ,它计算已处理的字节并具有回调。

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

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

    }

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

这是来自ProgressHttpEntityWrapper的完整代码:https://github.com/x2on/gradle-hockeyapp-plugin/blob/master/src/main/groovy/de/felixschulze/gradle/util/ProgressHttpEntityWrapper.groovy

该解决方案的主要来源:https://stackoverflow.com/a/7319110/268795


更多相关内容:请点击查看