我想要一些帮助,澄清使用HttpAsyncClient和multipart实体。基本上我正在尝试使用HttpAsyncClient将文件(byte [])的内容上传为MultiPart Body。 我如何使用它的示例:
CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();
httpAsyncClient.start();
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.addPart("file",new ByteArrayBody(Base64.decodeBase64(fileContent),"");
reqEntity.addPart("fileSize",new StringBody("1234"));
reqEntity.addPart("fileName",new StringBody("xyz.txt"));
reqEntity.addPart("fileType",new StringBody("text/plain"));
reqEntity.addPart("SEQ_NUM",new StringBody("23432"));
HttpPost httppost = new HttpPost(endpointUrl);
httppost.setEntity(reqEntity.build());
Future<HttpResponse> future = httpAsyncClient.execute(httppost, null);
httpAsyncClient.close();
以下是为此实施添加到项目中的Pom Dependences:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>
现在,我被阻止在引发以下异常的地方:
java.util.concurrent.ExecutionException:java.lang.UnsupportedOperationException:Multipart表单实体未实现#getContent()
我通过互联网进行了大量搜索,并且可以找到有关新的HttpAsyncClient实现的非常少的细节。我发现一些用户被问到类似的问题,但没有一个解决方案适合我。
[HttpAsyncClient多部分实体无法正常工作?] 在下面的链接中,用户建议使用BufferedHttpEntity包装MultipartEntity实例。所以,我更新了下面的代码(不确定它是否正确),但仍然是相同的异常。
CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();
httpAsyncClient.start();
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.addPart("file",new ByteArrayBody(Base64.decodeBase64(fileContent),"");
reqEntity.addPart("fileSize",new StringBody("1234"));
reqEntity.addPart("fileName",new StringBody("xyz.txt"));
reqEntity.addPart("fileType",new StringBody("text/plain"));
reqEntity.addPart("SEQ_NUM",new StringBody("23432"));
HttpPost httppost = new HttpPost(endpointUrl);
httppost.setEntity(new BufferedHttpEntity(reqEntity.build()));
Future<HttpResponse> future = httpAsyncClient.execute(httppost, null);
httpAsyncClient.close();
感谢您帮助确定原因。
参考文献:
答案 0 :(得分:0)
不能异步使用MultipartFormEntity。其中一个选项是将实体写入ByteArrayOutputStream并从中创建NByteArrayEntity。
File file = new File(filePath);
ByteArrayBody body;
body = new ByteArrayBody(FileUtils.readFileToByteArray(file), file.getName());
HttpEntity mEntity = MultipartEntityBuilder.create()
.setBoundary("-------------" + boundary)
.addPart("file", body)
.build();
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
mEntity.writeTo(baoStream);
HttpEntity nByteEntity = new NByteArrayEntity(baoStream.toByteArray(), ContentType.MULTIPART_FORM_DATA);
httppost.setEntity(nByteEntity );