带有进度的HttpClient Post和MultipartEntityBuilder

时间:2014-04-08 09:24:03

标签: java progress apache-httpclient-4.x

我尝试使用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 个答案:

答案 0 :(得分:15)

我刚刚找到了解决方案:

您需要HttpEntityWrapper来计算已处理的字节并进行回调。

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

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

    }

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

以下是ProgressHttpEntityWrapperhttps://github.com/x2on/gradle-hockeyapp-plugin/blob/master/src/main/groovy/de/felixschulze/gradle/util/ProgressHttpEntityWrapper.groovy

的完整代码

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