当前位置: 首页 > news >正文

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

1、环境准备:

<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>

2、Java中发送httpClient请求:

/*** HttpClient post multipart/form-data数据实现多文件上传* @param url* @param headers 头部参数* @param body body参数,json字符串* @param multipartFiles 文件列表* @param fileParName 接收的文件名* @return*/public static String sendFilePost(String url, Map<String, String> headers, String body,List<MultipartFile> multipartFiles,String fileParName) {CloseableHttpClient httpclient = HttpClients.createDefault();HttpPost httppost = new HttpPost(url);MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));//单个文件String fileName = null;MultipartFile multipartFile = null;for (int i = 0; i < multipartFiles.size(); i++) {//第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了//第三个参数是文件名//3)multipartFile = multipartFiles.get(i);fileName = multipartFile.getOriginalFilename();InputStream inputStream = null;try {inputStream = multipartFile.getInputStream();} catch (IOException e) {e.printStackTrace();}builder.addBinaryBody(fileParName,inputStream, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流}//4)构建请求参数 普通表单项/*	StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);builder.addPart("id", stringBody);*///决中文乱码ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, Consts.UTF_8);builder.addTextBody("paramStr", body, contentType);HttpEntity entity = builder.build();if (null!=headers&&headers.size()>0){for (Map.Entry<String, String> entry : headers.entrySet()) {httppost.addHeader(entry.getKey(),entry.getValue());}}httppost.setEntity(entity);CloseableHttpResponse response = null;try {response = httpclient.execute(httppost);} catch (IOException e) {logger.error("请求出错:" + url, e);return null;}String result = null;try {if(response!=null){HttpEntity httpEntity = response.getEntity();if (httpEntity != null && response.getStatusLine().getStatusCode()== HttpURLConnection.HTTP_OK) {// 判断请求状态result = EntityUtils.toString(httpEntity);}}} catch (Exception e) {logger.error("请求出错:" + url, e);} finally {try {if(response!=null){response.close();}} catch (IOException e) {logger.error("请求出错:" + url, e);}}logger.info("请求的URL:" + url + ", 返回结果:" + result);return result;}

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

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

4、模拟2中调用

/**将普通文件转成MultipartFile文件*/
public static MultipartFile getMultipartFile(File file) {FileItem item = new DiskFileItemFactory().createItem("file", MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());try (InputStream input = new FileInputStream(file);OutputStream os = item.getOutputStream()) {// 流转移IOUtils.copy(input, os);} catch (Exception e) {throw new IllegalArgumentException("Invalid file: " + e, e);}return new CommonsMultipartFile(item);
}public static void main(String[] args) {String url = "请求的服务路径";File f = new File("D:\\test");File[] files = f.listFiles();List<MultipartFile> multiFiles = new ArrayList();for(File tempFile:files){MultipartFile cMultiFile = getMultipartFile(tempFile);multiFiles.add(cMultiFile);}String restr = sendFilePost(url, null, JSON.toJSONString(paramMap),multiFiles,"file");
}

http://www.lryc.cn/news/240010.html

相关文章:

  • TMUX设置鼠标滚轮滑动来浏览之前的前面内容
  • 「go查漏补缺」命名规则以及 GROM 结构体的应用
  • Django 集成 Celery 实现高效的异步任务处理
  • Java之异常(上):基本异常体系
  • 你的关联申请已发起,请等待企业微信的管理员确认你的申请
  • .nvmrc 文件使用详解
  • 深度学习之基于YoloV5抽烟检测系统
  • 解释器模式 (Interpreter Pattern)
  • 【bug】uniapp的image组件渲染gif图,只有第一次点击的时候有动效,需要每次点击都有gif效果,已解决
  • ubuntu编译sqlite3并使用
  • 【OpenCV+OCR】计算机视觉:识别图像验证码中指定颜色文字
  • 【ROS 2 进阶-MoveIt!】MoveIt!中的关键节点
  • -bash: jps: command not found
  • [CLickhouse] 学习小计
  • 一款非常优秀的项目管理工具:进度猫(推荐)
  • Bert学习笔记(简单入门版)
  • 信号功率放大器的工作原理和特点是什么
  • 基于go标准分层架构项目设计实现
  • 原理Redis-IntSet
  • 逸学java【初级菜鸟篇】9.3 Stream流
  • html页面直接使用elementui Plus时间线 + vue3
  • 信息压缩模型在自然语言处理中的应用和探讨
  • 新版mmdetection3d将3D bbox绘制到图像
  • 合伙人注册即得/创业平台扶持!
  • 02_使用API_String
  • Spring IOC/DI和MVC及若依对应介绍
  • python的多层嵌套循环时,break可以退出多层循环吗?
  • 链表OJ--上
  • 内衣洗衣机哪些品牌质量好实惠?小型洗衣机全自动
  • 推荐一款适合做智慧旅游的前端模板