Java-MultipartFile批量Http上传

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<>();
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值