CloseableHttpClient以post方式调用第三方接口,以form-data 形式 发送 MultipartFile 文件数据

一:引入pom.xml

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

二:controller类实现

    @PostMapping("/upload")
    public JSONObject uploadOssFile(@RequestParam("files") MultipartFile files,
                                    @RequestParam("param1") String param1,
                                    @RequestParam("param2") String param2
                                    HttpServletRequest request) throws IOException {
        //获取上传文件 MultipartFile(图片,文件都可以)
        Map<String, String> map = new HashMap<>();
        map.put("param1", param1);
        map.put("param2", param2);
        return fileRemote.uploadFile(files, map);
    }

三:fileRemote实现

   
    public String getUrl() {
        return "http://?????";  文件上传的地址
    }



    /**
     *
     * @param multipartFile
     * @param map
     * @return
     * @throws IOException
     */
    public JSONObject uploadFile(MultipartFile multipartFile,
                             Map<String, String> map,
                             String toke) throws IOException {
        return JSONObject.parseObject(HttpsUtils.doPostFormData(getUrl(),"files", multipartFile, map ));
    }

四:HttpsUtils实现

/**
     * 以post方式调用第三方接口,以form-data 形式  发送 MultipartFile 文件数据
     *
     * @param url  post请求url
     * @param fileParamName 文件参数名称
     * @param multipartFile  文件
     * @param paramMap 表单里其他参数
     * @return
     */
    public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) {
        CloseableHttpClient httpClient2 = HttpClients.createDefault();
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
        //httpPost.setHeader("key", value);  // 这里放请求头参数

        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);

        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            String fileName = multipartFile.getOriginalFilename();
            // 文件流
            builder.addBinaryBody(fileParamName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            //表单中其他参数
            for(Map.Entry<String, String> entry: paramMap.entrySet()) {
                builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient2.execute(httpPost);// 执行提交
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用HttpPost失败!" + e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("关闭HttpPost连接失败!");
                }
            }
        }
        return null;
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值