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

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


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

maven依赖

<dependency>
    <groupId>commons-httpclientgroupId>
    <artifactId>commons-httpclientartifactId>
    <version>3.1version>
dependency>
<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpmimeartifactId>
    <version>4.5.3version>
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 httpPostRequest2(String url, List multipartFiles,String fileParName,
        Map params, int timeout) {
    Map resultMap = new HashMap();
    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 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;
    }
}

你可能感兴趣的:(Java,多文件上传,post上传文件,HttpClient4.5)