Hutool是一个小而全的Java工具类库
官方地址: https://www.hutool.cn/docs/#/
本文主要简单介绍Hutool的Http客户端工具类-HttpUtil和Hutool-json的简单使用
1、添加依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.6</version>
</dependency>
2、发送请求
// 发送携带参数的get请求
HashMap<String, Object> paramMap= new HashMap<>(1);
paramMap.put("pageNum", 1);
paramMap.put("pageSize", 5);
String result= HttpUtil.get("http://xxxx",paramMap);
3、对返回的参数进行解析
第一种数据类型:
[
{
"id": "1",
"number": 2,
},
{
"id": "2",
"number": 5,
}
]
hutool解析方式
JSONArray array = JSONUtil.parseArray(result);
for (JSONObject jsonObj : array.jsonIter()) {
System.out.println(jsonObj.getStr("id"));
System.out.println(jsonObj.getInt("number"));
}
第二种数据类型
{
"count": 210,
"person": [
{
"id": "2",
"number": 5
},
{
"id": "3",
"number":6,
}
]
}
只获取单个获取person数组对象
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("person");
for (JSONObject jsonObj : jsonArray.jsonIter()) {
System.out.println(jsonObj.getStr("id"));
System.out.println(jsonObj.getInt(number));
}
获取单个数组
JSONArray jsonArray=jsonObject.getJSONArray("ids");
List<Long> ids=jsonArray.toList(Long.class);