记录 通过 hutool 使用 HttpRequest 获取 URL 返回的 JSON并解析

1、首先需要 hutool-all-5.5.4.jar 包 可以直接在 https://repo1.maven.org/maven2/cn/hutool/hutool-all/5.5.4/

下载

2、通过里面拥有的源码分析,有很多常用的方法,post、get等等img点击并拖拽以移动

这里放一个最常用的例子:

1
2
3
HttpResponse res = HttpRequest.get("你的url")
.contentType("application/json")
.header("X-Auth-Token", findToken().execute();//findToken是这个url的token信息,如果不需要就不写,contentType具体看url中需要的是什么类型

点击并拖拽以移动

3、解析获取的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//遍历成为JSON对象
JSONObject jsonObject = JSON.parseObject(res.body());
JSONArray jsonArray =jsonObject.getJSONArray("servers");
//存储数据到pd
for (int i = 0; i < jsonArray.size(); i++) {//遍历jsonArray
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Map map = new HashMap();
map.put("test", jsonObject1.getString("test"));//将获取的信息保存到数组中,以便后面存储到数据库
//如果获取jsonObject1中的元素依旧是个数组,就继续遍历
JSONObject ob = (JSONObject) jsonObject1.get("test2");
JSONArray jsonArray2 =ob.getJSONArray("public");
for (int j = 0; j < jsonArray2.size(); j++) {
JSONObject jsonObject2 = jsonArray2.getJSONObject(j);
map.put("test22", jsonObject1.getString("test22"));

}
}

记录 通过 hutool 使用 HttpRequest 获取 URL 返回的 JSON并解析
https://tdsgpo.top/2022/04/02/记录 通过 hutool 使用 HttpRequest 获取 URL 返回的 JSON并解析/
作者
DDS
发布于
2022年4月2日
许可协议