前端提交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实现:

@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;
    }
}
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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值