使用HttpClient4 5 post提交multipart/form-data数据实现多文件上传

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

使用HttpClient4.5 post提交multipart/form-data数据实现多文件上传


  • 场景:前端提交multipart/form-data数据,由api服务A将请求转发到api服务B。

maven依赖

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.3</version>
</dependency>

HttpUtil实现

/**
* 使用HttpClient4.5 post提交multipart/form-data数据实现多文件上传
* @param url 请求地址
* @param multipartFiles post提交的文件列表
* @param fileParName fileKey
* @param params 附带的文本参数
* @param timeout 请求超时时间(毫秒)
* @return
* @author alexli
* @date 2018年5月8日 上午10:26:15
*/
public static Map<String, String> httpPostRequest2(String url, List<MultipartFile> multipartFiles,String fileParName,
        Map<String, Object> params, int timeout) {
    Map<String, String> resultMap = new HashMap<String, String>();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String result = "";
    try {
    HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        String fileName = null;
        MultipartFile multipartFile = null;
        for (int i = 0; i < multipartFiles.size(); i++) {
            multipartFile = multipartFiles.get(i);
            fileName = multipartFile.getOriginalFilename();
            builder.addBinaryBody(fileParName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
        }
        //决中文乱码
            ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if(entry.getValue() == null)
                continue;
            // 类似浏览器表单提交,对应input的name和value
            builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
        }
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);// 执行提交

        // 设置连接超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
        httpPost.setConfig(requestConfig);

        HttpEntity responseEntity = response.getEntity();
        resultMap.put("scode", String.valueOf(response.getStatusLine().getStatusCode()));
        resultMap.put("data", "");
        if (responseEntity != null) {
            // 将响应内容转换为字符串
            result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
            resultMap.put("data", result);
        }
    } catch (Exception e) {
        resultMap.put("scode", "error");
        resultMap.put("data", "HTTP请求出现异常: " + e.getMessage());

        Writer w = new StringWriter();
        e.printStackTrace(new PrintWriter(w));
        logger.error("HTTP请求出现异常: " + w.toString());
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return resultMap;
}

demo

@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> add(HttpServletRequest request) throws Exception {
    MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
    Map<String, Object> data = new HashMap<>();
    data.put("code", params.getParameter("code"));
    data.put("name", params.getParameter("name"));
    Map<String, String> resultDataMap = HttpUtil.httpPostRequest2("转发API地址",params.getFiles("files"), "files", data, -1);
    if ("200".equals(resultDataMap.get("scode"))) {
        Map<String, Object> returnData = JsonUtil.reflect(MapUtil.getString(resultDataMap, "data"));
        super.setOutData(returnData);
        return returnData;
    }
}

点这里可以跳转到人工智能网站

发表评论