当前位置:   article > 正文

通过httpclient发送请求的几种方式,发送文件、参数、json对象_httpclient 传递文件流和参数

httpclient 传递文件流和参数

使用工具:idea

框架:gradle、springboot

实现目标:使用 httpclient 发送文件/参数/json对象

method:post

主要用到的jar包:

  1. compile group: 'net.sf.json-lib', name: 'json-lib', version: '2.4', classifier: 'jdk15'
  2. //httpclient
  3. // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
  4. compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'
  5. // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime
  6. compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.3'
  7. // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore
  8. compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.6'

花了大半天终于写完这个测试类,能正常跑起来,下面主要贴出来两种 httpclient 的发送和接收,基本够用

特别注意:

  1. 文件和json对象是不能一起发送的,要发也是把json对象toString一下,见第一个方法
  2. 发送json对象,并用Requestbody接收,这种智能发对象,不能发文件,见第二个方法

预备几个方法,因为模拟数据用到的一样,所以先贴这几个公用方法:

  1. //模拟文件数据,这里自己改成自己的文件就可以了
  2. private static List<Map<String, Object>> getFileList() {
  3. //文件列表,搞了三个本地文件
  4. List<Map<String, Object>> fileList = new ArrayList<>();
  5. Map<String, Object> filedetail1 = new HashMap<>();
  6. filedetail1.put("location", "F:\\me\\photos\\动漫\\3ba39425fec1965f4d088d2f.bmp");
  7. filedetail1.put("fileName", "图片1");
  8. fileList.add(filedetail1);
  9. Map<String, Object> filedetail2 = new HashMap<>();
  10. filedetail2.put("location", "F:\\me\\photos\\动漫\\09b3970fd3f5cc65b1351da4.bmp");
  11. filedetail2.put("fileName", "图片2");
  12. fileList.add(filedetail2);
  13. Map<String, Object> filedetail3 = new HashMap<>();
  14. filedetail3.put("location", "F:\\me\\photos\\动漫\\89ff57d93cd1b72cd0164ec9.bmp");
  15. filedetail3.put("fileName", "图片3");
  16. fileList.add(filedetail3);
  17. return fileList;
  18. }
  19. //模拟json对象数据
  20. private static JSONObject getJsonObj() {
  21. /**
  22. * 这里搞json对象方法很多
  23. * 1.直接字符串贴过来,然后解析成json
  24. * 2.用map<String,Object>,做好数据之后解析成json,.toJSONString
  25. * 3.new 一个JSONObject对象,然后自己拼接
  26. * 下面的例子用map好了,这个应该通俗易懂
  27. */
  28. Map<String, Object> main = new HashMap<>();
  29. main.put("token", "httpclient with file stringParam jsonParam and jasonArrayParam");
  30. List<Map<String, Object>> contentList = new ArrayList<>();
  31. for (int i = 0; i < 4; i++) {
  32. Map<String, Object> content = new HashMap<>();
  33. content.put("id", i);
  34. content.put
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/302829
推荐阅读
相关标签
  

闽ICP备14008679号