MultipartFile批量Http上传
Pom依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.12</version>
</dependency>
Http调用代码
public static Map<String, Object> upload(String url, MultipartFile[] files,
Map<String, String> headerParams,
Map<String, String> otherParams) throws IOException {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (Objects.nonNull(headerParams)) {
for (Map.Entry<String, String> e : headerParams.entrySet()) {
httpPost.addHeader(e.getKey(), e.getValue());
}
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
builder.addBinaryBody("files", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
}
if (Objects.nonNull(otherParams)) {
for (Map.Entry<String, String> e : otherParams.entrySet()) {
builder.addTextBody(e.getKey(), e.getValue(), ContentType.create("text/plain", StandardCharsets.UTF_8));
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
Map<String, Object> resultMap = new HashMap<>();
if (response.getStatusLine().getStatusCode() == 200) {
String body = EntityUtils.toString(responseEntity);
resultMap.put("code", 200);
resultMap.put("msg", "xxxx");
resultMap.put("body", body);
}
return resultMap;
} catch (Exception e) {
log.error("xxxx", e);
} finally {
if (Objects.nonNull(httpClient)) {
httpClient.close();
}
}
return new HashMap<>();
}