java – HttpClient发布进度和MultipartEntityBuilder

前端之家收集整理的这篇文章主要介绍了java – HttpClient发布进度和MultipartEntityBuilder前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试使用HttpClient 4.3.3和MultipartEntityBuilder上传文件时实现进度

所以实际上我用以下代码执行一个post请求

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而且对我来说不起作用……

解决方法

我刚刚找到了解决方案:

您需要一个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

原文链接:https://www.f2er.com/java/128067.html

猜你在找的Java相关文章