发送POST请求,包含文件MultipartFile参数,普通字符串参数,请求头参数

在与别人对接时经常会遇到既发送文件参数又发送字符串参数的请求,遇到这种情况请求的核心就是:

文件参数的ContenType=multipart/form-data

字符串参数的ContenType=application/json

 一、post请求工具类

/**
     * 使用httpclint 发送文件,如果不传输文件,直接设置fileParams=null,
     * 如果不设置请求头参数,直接设置headerParams=null,就可以进行普通参数的POST请求了
     *
     * @param url          请求路径
     * @param fileParams   文件参数
     * @param otherParams  其他字符串参数
     * @param headerParams 请求头参数
     * @return
     */
    public static String uploadFile(String url, Map<String, MultipartFile> fileParams, Map<String, String> otherParams, Map<String, String> headerParams) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            if (headerParams != null && headerParams.size() > 0) {
                for (Map.Entry<String, String> e : headerParams.entrySet()) {
                    String value = e.getValue();
                    String key = e.getKey();
                    if (StringUtils.isNotBlank(value)) {
                        httpPost.setHeader(key, value);
                    }
                }
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            //    文件传输http请求头(multipart/form-data)
            if (fileParams != null && fileParams.size() > 0) {
                for (Map.Entry<String, MultipartFile> e : fileParams.entrySet()) {
                    String fileParamName = e.getKey();
                    MultipartFile file = e.getValue();
                    if (file != null) {
                        String fileName = file.getOriginalFilename();
                        builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
                    }
                }
            }
            //    字节传输http请求头(application/json)
            ContentType contentType = ContentType.create("application/json", Charset.forName("UTF-8"));
            if (otherParams != null && otherParams.size() > 0) {
                for (Map.Entry<String, String> e : otherParams.entrySet()) {
                    String value = e.getValue();
                    if (StringUtils.isNotBlank(value)) {
                        builder.addTextBody(e.getKey(), value, contentType);// 类似浏览器表单提交,对应input的name和value
                    }
                }
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

 二、main方法调用示例

    public static void main(String[] args) throws Exception{
        String URL = "http://IP:PORT/test";
        String picPath1 = "D://";
        String picPath2 = "D://";
        String arg1 = "入参1";
        String arg2 = "入参2";
        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("token", "testToken");

        Map<String, MultipartFile> fileParams = new HashMap<>();
        //本地文件转为MultipartFile
//        String picPath = "/var/111.png";
        MultipartFile file1 = FileUtil.pathToMultipartFile(picPath1);
        MultipartFile file2 = FileUtil.pathToMultipartFile(picPath2);
        //url转为MultipartFile
//        MultipartFile fileItem = FileUtils.urlToMutipartFile("https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg", "asdfasdf.png");
        fileParams.put("file2", file1);
        fileParams.put("file1", file2);

        Map<String, String> otherParams = new HashMap<>();
        otherParams.put("arg1", arg1);
        otherParams.put("arg2", arg2);

        String res = uploadFilePost(URL, fileParams, otherParams, headerParams);

        System.out.println(res);
    }

三、FileUtil 代码示例

java将File转换成MultipartFile_L.CHAO的博客-CSDN博客_file转multipartfile

public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 本地文件转为MultipartFile
     *
     * @param picPath
     * @return
     */
    public static MultipartFile pathToMultipartFile(String picPath) throws Exception{
        FileItem fileItem = createFileItem(picPath);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    /**
     * 将file转换成fileItem
     *
     * @param filePath
     * @return
     */
    public static FileItem createFileItem(String filePath) throws Exception{
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";

        FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName");
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(newfile);
            os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            logger.error("createFileItem:文件转换异常!",e);
            throw e;
        } finally {
            try {
                if (null != os){
                    os.close();
                }
                if (null != fis){
                    fis.close();
                }
            } catch (IOException e) {
                logger.error("createFileItem:关流异常!",e);
            }
        }
        return item;
    }
}

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用Spring的RestTemplate来发送MultipartFile、Date、Integer的请求。这里提供一个简单的示例: ```java @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date, @RequestParam("count") int count) { // 处理文件上传、日期和计数参数 return "File uploaded successfully!"; } } ``` 在这个示例,我们将发送一个包含MultipartFile、Date和Integer参数POST请求。@RequestParam注解用于将请求参数绑定到方法参数上。@DateTimeFormat注解用于指定日期的格式。 然后使用RestTemplate发送请求: ```java RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("file", new FileSystemResource("path/to/file")); map.add("date", "2021-06-01"); map.add("count", 10); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers); String url = "http://localhost:8080/upload"; ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); ``` 在这个示例,我们使用MultiValueMap来设置请求参数。这个MultiValueMap可以包含多个键值对,每个键值对可以是一个字符串或一个文件。我们还需要设置请求头的Content-Type为multipart/form-data。 最后,我们使用RestTemplate发送POST请求,并将响应转换为字符串
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值