• HttpClient发送MultipartFile多文件及多参数请求


    1、环境准备:

    1. <dependency>
    2. <groupId>commons-httpclientgroupId>
    3. <artifactId>commons-httpclientartifactId>
    4. <version>3.1version>
    5. dependency>
    6. <dependency>
    7. <groupId>org.apache.httpcomponentsgroupId>
    8. <artifactId>httpmimeartifactId>
    9. <version>4.5.3version>
    10. dependency>

    2、Java中发送httpClient请求:

    1. /**
    2. * HttpClient post multipart/form-data数据实现多文件上传
    3. * @param url
    4. * @param headers 头部参数
    5. * @param body body参数,json字符串
    6. * @param multipartFiles 文件列表
    7. * @param fileParName 接收的文件名
    8. * @return
    9. */
    10. public static String sendFilePost(String url, Map headers, String body,List multipartFiles,String fileParName) {
    11. CloseableHttpClient httpclient = HttpClients.createDefault();
    12. HttpPost httppost = new HttpPost(url);
    13. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    14. builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    15. builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
    16. //单个文件
    17. String fileName = null;
    18. MultipartFile multipartFile = null;
    19. for (int i = 0; i < multipartFiles.size(); i++) {
    20. //第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
    21. //第三个参数是文件名
    22. //3)
    23. multipartFile = multipartFiles.get(i);
    24. fileName = multipartFile.getOriginalFilename();
    25. InputStream inputStream = null;
    26. try {
    27. inputStream = multipartFile.getInputStream();
    28. } catch (IOException e) {
    29. e.printStackTrace();
    30. }
    31. builder.addBinaryBody(fileParName,inputStream, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
    32. }
    33. //4)构建请求参数 普通表单项
    34. /* StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);
    35. builder.addPart("id", stringBody);*/
    36. //决中文乱码
    37. ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, Consts.UTF_8);
    38. builder.addTextBody("paramStr", body, contentType);
    39. HttpEntity entity = builder.build();
    40. if (null!=headers&&headers.size()>0){
    41. for (Map.Entry entry : headers.entrySet()) {
    42. httppost.addHeader(entry.getKey(),entry.getValue());
    43. }
    44. }
    45. httppost.setEntity(entity);
    46. CloseableHttpResponse response = null;
    47. try {
    48. response = httpclient.execute(httppost);
    49. } catch (IOException e) {
    50. logger.error("请求出错:" + url, e);
    51. return null;
    52. }
    53. String result = null;
    54. try {
    55. if(response!=null){
    56. HttpEntity httpEntity = response.getEntity();
    57. if (httpEntity != null && response.getStatusLine().getStatusCode()== HttpURLConnection.HTTP_OK) {// 判断请求状态
    58. result = EntityUtils.toString(httpEntity);
    59. }
    60. }
    61. } catch (Exception e) {
    62. logger.error("请求出错:" + url, e);
    63. } finally {
    64. try {
    65. if(response!=null){
    66. response.close();
    67. }
    68. } catch (IOException e) {
    69. logger.error("请求出错:" + url, e);
    70. }
    71. }
    72. logger.info("请求的URL:" + url + ", 返回结果:" + result);
    73. return result;
    74. }

    3、后端服务restful接口接参:

    1. @Operation(summary = "获取附件")
    2. @PostMapping("/xxx")
    3. private void sendfilepost(@RequestParam(value = "file") List mulFiles,@RequestParam(value = "paramStr") String json){
    4. /**这里处理自己的逻辑*/
    5. }

    4、模拟2中调用

    1. /**将普通文件转成MultipartFile文件*/
    2. public static MultipartFile getMultipartFile(File file) {
    3. FileItem item = new DiskFileItemFactory().createItem("file"
    4. , MediaType.MULTIPART_FORM_DATA_VALUE
    5. , true
    6. , file.getName());
    7. try (InputStream input = new FileInputStream(file);
    8. OutputStream os = item.getOutputStream()) {
    9. // 流转移
    10. IOUtils.copy(input, os);
    11. } catch (Exception e) {
    12. throw new IllegalArgumentException("Invalid file: " + e, e);
    13. }
    14. return new CommonsMultipartFile(item);
    15. }
    16. public static void main(String[] args) {
    17. String url = "请求的服务路径";
    18. File f = new File("D:\\test");
    19. File[] files = f.listFiles();
    20. List multiFiles = new ArrayList();
    21. for(File tempFile:files){
    22. MultipartFile cMultiFile = getMultipartFile(tempFile);
    23. multiFiles.add(cMultiFile);
    24. }
    25. String restr = sendFilePost(url, null, JSON.toJSONString(paramMap),multiFiles,"file");
    26. }

  • 相关阅读:
    Latex论文排版
    scrcpy macos 编译安装最新版 1.2.4
    构建RAG应用-day01: 词向量和向量数据库 文档预处理
    1.5-07:奥运奖牌计数
    Redis实战——分布式锁
    vue用axios在页面直接调用接口完整版(代码源码)最新(四)
    R语言检索网址汇总
    2. SCI论文引言写作案例分析学习笔记
    MySQL 数据处理之增删改
    超算云平台在线功能Q-Flow、Q-Studio V2.1版本升级,web端在线建模+DFT计算
  • 原文地址:https://blog.csdn.net/fraya1234/article/details/134524193