赞
踩
使用工具:idea
框架:gradle、springboot
实现目标:使用 httpclient 发送文件/参数/json对象
method:post
主要用到的jar包:
- compile group: 'net.sf.json-lib', name: 'json-lib', version: '2.4', classifier: 'jdk15'
-
- //httpclient
- // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
- compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.3'
- // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime
- compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.3'
- // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore
- compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.6'
花了大半天终于写完这个测试类,能正常跑起来,下面主要贴出来两种 httpclient 的发送和接收,基本够用
特别注意:
- 文件和json对象是不能一起发送的,要发也是把json对象toString一下,见第一个方法
- 发送json对象,并用Requestbody接收,这种智能发对象,不能发文件,见第二个方法
预备几个方法,因为模拟数据用到的一样,所以先贴这几个公用方法:
-
- //模拟文件数据,这里自己改成自己的文件就可以了
- private static List<Map<String, Object>> getFileList() {
- //文件列表,搞了三个本地文件
- List<Map<String, Object>> fileList = new ArrayList<>();
- Map<String, Object> filedetail1 = new HashMap<>();
- filedetail1.put("location", "F:\\me\\photos\\动漫\\3ba39425fec1965f4d088d2f.bmp");
- filedetail1.put("fileName", "图片1");
- fileList.add(filedetail1);
- Map<String, Object> filedetail2 = new HashMap<>();
- filedetail2.put("location", "F:\\me\\photos\\动漫\\09b3970fd3f5cc65b1351da4.bmp");
- filedetail2.put("fileName", "图片2");
- fileList.add(filedetail2);
- Map<String, Object> filedetail3 = new HashMap<>();
- filedetail3.put("location", "F:\\me\\photos\\动漫\\89ff57d93cd1b72cd0164ec9.bmp");
- filedetail3.put("fileName", "图片3");
- fileList.add(filedetail3);
- return fileList;
- }
-
- //模拟json对象数据
- private static JSONObject getJsonObj() {
- /**
- * 这里搞json对象方法很多
- * 1.直接字符串贴过来,然后解析成json
- * 2.用map<String,Object>,做好数据之后解析成json,.toJSONString
- * 3.new 一个JSONObject对象,然后自己拼接
- * 下面的例子用map好了,这个应该通俗易懂
- */
- Map<String, Object> main = new HashMap<>();
- main.put("token", "httpclient with file stringParam jsonParam and jasonArrayParam");
- List<Map<String, Object>> contentList = new ArrayList<>();
- for (int i = 0; i < 4; i++) {
- Map<String, Object> content = new HashMap<>();
- content.put("id", i);
- content.put

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。