目录
一、Hutool介绍
二、笔者的话
三、引入依赖
四、大致步骤
五、GET请求
5.1 代码
5.2 结果展示
六、POST请求
6.1 代码一(Form Data类型参数)
6.2 结果展示
6.3 代码二(Form Data类型参数 - 含上传文件)
6.4 结果展示
6.5 代码三 (Request Payload,即JSON格式的参数)
6.6 结果展示
七、处理响应主体(JSON工具的使用)
一、Hutool介绍
以下来自官网🚚🚚🚚:Hutool参考文档
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
Hutool中的工具方法来自每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当;
Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。
Hutool名称的由来
Hutool = Hu + tool,是原公司项目底层代码剥离后的开源库,“Hu”是公司名称的表示,tool表示工具。Hutool谐音“糊涂”,一方面简洁易懂,一方面寓意“难得糊涂”。
二、笔者的话
如何使用其实官网文档已经很详细了,我为什么要单独写一篇教程,主要目的是方便个人巩固熟练,如果也能帮助到你,那是我的荣幸!❤️💛💙💚💜🤎
三、引入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.1</version>
</dependency>
四、大致步骤
- 构建一个http请求 - 请求的哪个地址
- 设置请求方式、请求头、请求参数等信息
- 执行请求,返回一个http响应类
- 然后通过这个相应类可以获取响应的主体、cookie、是否请求成功等信息
- 要获取具体某些信息,主要就是在主体上进行操作了
五、GET请求
5.1 代码
@GetMapping("test")
public Result<String> test(String username,String password){
return Result.success(username + " " + password);
}
public static void main(String[] args){
// 1. 创建HttpRequest对象 - 指定好 url 地址
HttpRequest httpRequest = new HttpRequest("http://10.77.78.73:8000/test/test");
// 2. 设置请求方式,默认是GET请求
httpRequest.setMethod(Method.GET);
// 3. 设置请求参数 可通过 form表单方法 设置
// form方法有很多重载方法,可以一个一个参数设置,也可以将参数封装进一个map集合然后一块儿传
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("username","牛飞");
httpRequest.form(paramsMap);
httpRequest.form("password", "123456");
httpRequest.form("username","阿祖");
// 4. 设置请求头
// 请求头同样可以逐一设置,也可以封装到map中再统一设置
// 设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
httpRequest.header("x-c-authorization","yourToken");
// 5. 执行请求,得到http响应类
HttpResponse execute = httpRequest.execute();
// 6. 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
System.out.println(ok);
List<HttpCookie> cookies = execute.getCookies();// 获取所有cookie
cookies.forEach(System.out::println); // 如果为空不会遍历的
String body = execute.body(); // 获取响应主体
System.out.println(body);
}
5.2 结果展示
六、POST请求
6.1 代码一(Form Data类型参数)
@LogAnnotation(module = "宠物分类",operation = "根据条件查询指定宠物分类信息")
@ApiOperation("根据条件查询指定宠物分类信息")
@PostMapping("/findPetCategoryListQuery")
public Result<List<PetCategoryVo>> findPetCategoryListQuery(@RequestParam("parentId") int parentId ,@RequestParam("hotFlag") int hotFlag ){
List<PetCategoryVo> list = petCategoryService.findPetCategoryListQuery(parentId,hotFlag);
return Result.success(list);
}
public static void main(String[] args) {
// 1. 创建HttpRequest对象 - 指定好 url 地址
HttpRequest httpRequest = new HttpRequest("http://10.77.78.73:8000/pethome/pet-category/findPetCategoryListQuery");
// 2. 设置请求方式,默认是GET请求
httpRequest.setMethod(Method.POST);
// 3. 设置请求参数 可通过 form表单方法 设置
// form方法有很多重载方法,可以一个一个参数设置,也可以将参数封装进一个map集合然后一块儿传
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("parentId","1");
paramsMap.put("hotFlag","1");
httpRequest.form(paramsMap);
// 4. 设置请求头
// 请求头同样可以逐一设置,也可以封装到map中再统一设置
// 设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
httpRequest.header("x-c-authorization","yourToken");
// 5. 执行请求,得到http响应类
HttpResponse execute = httpRequest.execute();
// 6. 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
System.out.println(ok);
List<HttpCookie> cookies = execute.getCookies();// 获取所有cookie
cookies.forEach(System.out::println); // 如果为空不会遍历的
String body = execute.body(); // 获取响应主体
System.out.println(body);
}
6.2 结果展示
true
{"code":1,"msg":"请求成功","data":[{"id":4,"parentId":1,"categoryName":"美国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/61449428.a76e175.jpg","createTime":"2023-08-13 16:59:11","updateTime":"2023-08-13 23:30:50","deleteFlag":0,"children":null},{"id":5,"parentId":1,"categoryName":"俄罗斯蓝猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:45","updateTime":"2023-08-13 17:04:38","deleteFlag":0,"children":null},{"id":6,"parentId":1,"categoryName":"布偶猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:56","updateTime":"2023-08-13 17:04:39","deleteFlag":0,"children":null},{"id":7,"parentId":1,"categoryName":"英国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/e919d872.xhscdn.jpg","createTime":"2023-08-13 17:00:31","updateTime":"2023-08-13 23:35:32","deleteFlag":0,"children":null},{"id":8,"parentId":1,"categoryName":"波斯猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:37","updateTime":"2023-08-13 17:04:42","deleteFlag":0,"children":null},{"id":9,"parentId":1,"categoryName":"苏格兰折耳猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:50","updateTime":"2023-08-13 17:04:43","deleteFlag":0,"children":null},{"id":10,"parentId":1,"categoryName":"暹罗猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:15","updateTime":"2023-08-13 17:04:46","deleteFlag":0,"children":null},{"id":11,"parentId":1,"categoryName":"咖啡猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:38","updateTime":"2023-08-13 17:05:17","deleteFlag":0,"children":null}]}
6.3 代码二(Form Data类型参数 - 含上传文件)
@ApiOperation("测试上传文件")
@PostMapping("uploadTest")
public Result<String> uploadTest(@RequestParam("image")MultipartFile file){
// 获取原始文件名称:如 aa.png
String originalFilename = file.getOriginalFilename();
// 修改成唯一的名称
originalFilename = UUID.randomUUID().toString().substring(0,8) + "." + originalFilename;
// 上传
boolean uploadFlag = qiniuUtils.upload(file, originalFilename);
if (uploadFlag){
return Result.success(qiniuUtils.url + originalFilename);
}else {
return Result.fail();
}
}
public static void main(String[] args) {
// 1. 创建HttpRequest对象 - 指定好 url 地址
HttpRequest httpRequest = new HttpRequest("http://10.77.78.73:8000/test/uploadTest");
// 2. 设置请求方式,默认是GET请求
httpRequest.setMethod(Method.POST);
// 3. 设置请求参数 可通过 form表单方法 设置 可以是文件类型
// form方法有很多重载方法,可以一个一个参数设置,也可以将参数封装进一个map集合然后一块儿
File file = new File("C:\\Users\\hssym\\Downloads\\UBQ.png");
httpRequest.form("image",file);
// 4. 设置请求头
// 请求头同样可以逐一设置,也可以封装到map中再统一设置
// 设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
httpRequest.header("x-c-authorization","yourToken");
// 5. 执行请求,得到http响应类
HttpResponse execute = httpRequest.execute();
// 6. 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
System.out.println(ok);
List<HttpCookie> cookies = execute.getCookies();// 获取所有cookie
cookies.forEach(System.out::println); // 如果为空不会遍历的
String body = execute.body(); // 获取响应主体
System.out.println(body);
}
6.4 结果展示
6.5 代码三 (Request Payload,即JSON格式的参数)
和代码一、代码二不同的是,这次我们前后端约定通过json的格式传递参数。
此时不能再用form方法设置参数了,需要改用它提供的body方法。
@LogAnnotation(module = "宠物分类",operation = "根据条件查询指定宠物分类信息")
@ApiOperation("根据条件查询指定宠物分类信息")
@PostMapping("/findPetCategoryListQuery")
public Result<List<PetCategoryVo>> findPetCategoryListQuery(@RequestBody QueryPetCategoryForm form){
List<PetCategoryVo> list = petCategoryService.findPetCategoryListQuery(form);
return Result.success(list);
}
public static void main(String[] args) {
// 1. 创建HttpRequest对象 - 指定好 url 地址
HttpRequest httpRequest = new HttpRequest("http://10.77.78.73:8000/pethome/pet-category/findPetCategoryListQuery");
// 2. 设置请求方式,默认是GET请求
httpRequest.setMethod(Method.POST);
// 3. 设置请求参数 前后端约定通过json格式传递参数,此时就不能用form方法了,改用它提供的body方法
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("parentId","1");
paramsMap.put("hotFlag","1");
String paramsJson = JSON.toJSONString(paramsMap);
httpRequest.body(paramsJson);// 需要转成json字符串
// 4. 设置请求头
// 请求头同样可以逐一设置,也可以封装到map中再统一设置
// 设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
httpRequest.header("x-c-authorization","yourToken");
// 5. 执行请求,得到http响应类
HttpResponse execute = httpRequest.execute();
// 6. 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
System.out.println(ok);
List<HttpCookie> cookies = execute.getCookies();// 获取所有cookie
cookies.forEach(System.out::println); // 如果为空不会遍历的
String body = execute.body(); // 获取响应主体
System.out.println(body);
}
6.6 结果展示
true
{"code":1,"msg":"请求成功","data":[{"id":4,"parentId":1,"categoryName":"美国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/61449428.a76e175.jpg","createTime":"2023-08-13 16:59:11","updateTime":"2023-08-13 23:30:50","deleteFlag":0,"children":null},{"id":5,"parentId":1,"categoryName":"俄罗斯蓝猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:45","updateTime":"2023-08-13 17:04:38","deleteFlag":0,"children":null},{"id":6,"parentId":1,"categoryName":"布偶猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:56","updateTime":"2023-08-13 17:04:39","deleteFlag":0,"children":null},{"id":7,"parentId":1,"categoryName":"英国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/e919d872.xhscdn.jpg","createTime":"2023-08-13 17:00:31","updateTime":"2023-08-13 23:35:32","deleteFlag":0,"children":null},{"id":8,"parentId":1,"categoryName":"波斯猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:37","updateTime":"2023-08-13 17:04:42","deleteFlag":0,"children":null},{"id":9,"parentId":1,"categoryName":"苏格兰折耳猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:50","updateTime":"2023-08-13 17:04:43","deleteFlag":0,"children":null},{"id":10,"parentId":1,"categoryName":"暹罗猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:15","updateTime":"2023-08-13 17:04:46","deleteFlag":0,"children":null},{"id":11,"parentId":1,"categoryName":"咖啡猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:38","updateTime":"2023-08-13 17:05:17","deleteFlag":0,"children":null}]}
ok,以上不管哪种请求,基本的方法是不变的,触类旁通。
七、处理响应主体(JSON工具的使用)
我们以post请求的代码三为例,它得到的响应主体结构如下:
{"code":1,"msg":"请求成功","data":[{"id":4,"parentId":1,"categoryName":"美国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/61449428.a76e175.jpg","createTime":"2023-08-13 16:59:11","updateTime":"2023-08-13 23:30:50","deleteFlag":0,"children":null},{"id":5,"parentId":1,"categoryName":"俄罗斯蓝猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:45","updateTime":"2023-08-13 17:04:38","deleteFlag":0,"children":null},{"id":6,"parentId":1,"categoryName":"布偶猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:56","updateTime":"2023-08-13 17:04:39","deleteFlag":0,"children":null},{"id":7,"parentId":1,"categoryName":"英国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/e919d872.xhscdn.jpg","createTime":"2023-08-13 17:00:31","updateTime":"2023-08-13 23:35:32","deleteFlag":0,"children":null},{"id":8,"parentId":1,"categoryName":"波斯猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:37","updateTime":"2023-08-13 17:04:42","deleteFlag":0,"children":null},{"id":9,"parentId":1,"categoryName":"苏格兰折耳猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:50","updateTime":"2023-08-13 17:04:43","deleteFlag":0,"children":null},{"id":10,"parentId":1,"categoryName":"暹罗猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:15","updateTime":"2023-08-13 17:04:46","deleteFlag":0,"children":null},{"id":11,"parentId":1,"categoryName":"咖啡猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:38","updateTime":"2023-08-13 17:05:17","deleteFlag":0,"children":null}]}
有了它,我们就能获取有关的数据了。这主要就是JSON工具的使用了。
我习惯上用fastjson,下述案例就以fastjson工具进行处理:
现在,我们希望获取到所有的分类名称。
public static void main(String[] args) {
HttpRequest httpRequest = new HttpRequest("http://10.77.78.73:8000/pethome/pet-category/findPetCategoryListQuery");
httpRequest.setMethod(Method.POST);
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("parentId","1");
paramsMap.put("hotFlag","1");
String paramsJson = JSON.toJSONString(paramsMap);
httpRequest.body(paramsJson);// 需要转成json字符串
httpRequest.header("x-c-authorization","yourToken");
HttpResponse execute = httpRequest.execute();
// 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
if (execute.isOk()){
String body = execute.body(); // 获取响应主体
System.out.println(body);
JSONObject bodyJsonObject = JSON.parseObject(body);// 将获取的响应主体解析成json对象
JSONArray dataJsonArray = bodyJsonObject.getJSONArray("data"); // 从json对象中获取指定属性的值,并将其转换成json数组(前提是该属性的值是数组结构)
if (dataJsonArray != null){
for (int i = 0; i < dataJsonArray.size(); i++) {
JSONObject dataItemJsonObject = dataJsonArray.getJSONObject(i); // 从json数组中获取json对象
String categoryName = dataItemJsonObject.getString("categoryName"); // 从json对象中获取指定属性的值
System.out.println(categoryName);
}
}
}
}
{"code":1,"msg":"请求成功","data":[{"id":4,"parentId":1,"categoryName":"美国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/61449428.a76e175.jpg","createTime":"2023-08-13 16:59:11","updateTime":"2023-08-13 23:30:50","deleteFlag":0,"children":null},{"id":5,"parentId":1,"categoryName":"俄罗斯蓝猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:45","updateTime":"2023-08-13 17:04:38","deleteFlag":0,"children":null},{"id":6,"parentId":1,"categoryName":"布偶猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 16:59:56","updateTime":"2023-08-13 17:04:39","deleteFlag":0,"children":null},{"id":7,"parentId":1,"categoryName":"英国短尾猫","level":2,"hotFlag":1,"img":"http://rzc4iq21h.hb-bkt.clouddn.com/e919d872.xhscdn.jpg","createTime":"2023-08-13 17:00:31","updateTime":"2023-08-13 23:35:32","deleteFlag":0,"children":null},{"id":8,"parentId":1,"categoryName":"波斯猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:37","updateTime":"2023-08-13 17:04:42","deleteFlag":0,"children":null},{"id":9,"parentId":1,"categoryName":"苏格兰折耳猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:00:50","updateTime":"2023-08-13 17:04:43","deleteFlag":0,"children":null},{"id":10,"parentId":1,"categoryName":"暹罗猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:15","updateTime":"2023-08-13 17:04:46","deleteFlag":0,"children":null},{"id":11,"parentId":1,"categoryName":"咖啡猫","level":2,"hotFlag":1,"img":null,"createTime":"2023-08-13 17:01:38","updateTime":"2023-08-13 17:05:17","deleteFlag":0,"children":null}]}
美国短尾猫
俄罗斯蓝猫
布偶猫
英国短尾猫
波斯猫
苏格兰折耳猫
暹罗猫
咖啡猫