我尝试使用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的完整代码