栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用hutool工具http请求并且解析json

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用hutool工具http请求并且解析json

Hutool 参考文档

导入依赖

	cn.hutool
	hutool-all
	4.1.2


一、http请求 1、get和post
HttpUtil.get(url,paramMap,timeOut);
HttpUtil.post(同上)

//=====

String url = "https://xxx/xx";//指定URL
Map map = new HashMap<>();//存放参数
map.put("A", 100);
map.put("B", 200);
HashMap headers = new HashMap<>();//存放请求头,可以存放多个请求头
headers.put("xxx", xxx);
//发送get请求并接收响应数据
String result= HttpUtil.createGet(url).addHeaders(headers).form(map).execute().body();
//发送post请求并接收响应数据
String result= HttpUtil.createPost(url).addHeaders(headers).form(map).execute().body();
2、发送del请求
String url = "https://xxx/delete/"+id;//指定URL携带ID
HashMap headers = new HashMap<>();//存放请求头,可以存放多个请求头
headers.put("xxx", xxx);
//发送delete请求并接收响应数据
String result= HttpUtil.createRequest(Method.DELETE, url).addHeaders(headers).execute().body();
3、原生
@Test
public void testHttps() throws Exception {
    JSONObject json = new JSONObject();
    json.put("username", "1332788xxxxxx");
    json.put("password", "123456.");
    String result = HttpRequest.post("https://api2.bmob.cn/1/users")
            .header("Content-Type", "application/json")//头信息,多个头信息多次调用此方法即可
            .header("X-Bmob-Application-Id","2f0419a31f9casdfdsf431f6cd297fdd3e28fds4af")
            .header("X-Bmob-REST-API-Key","1e03efdas82178723afdsafsda4be0f305def6708cc6")
            .body(json)
            .execute().body();
       System.out.println(result);   
}
二、http结果集json解析(采用阿里的或者是hutool工具)

    com.alibaba
    fastjson
    1.2.70

转换成json字符串

  List userList = new ArrayList<>();
        User user = new User();
        user.setName("123");
        userList.add(user);
        //实体类转换json
        JSON.toJSONString(user)
        //list转换json
		JSON.toJSONString(userList)

转换成对象

public class Json {
    public static void main(String[] args) {
    //实体
        String json = "{"age":20,"name":"name0"}";
        JSON.parseObject(json, User.class);
        //list集合
        String json = "[{"age":20,"name":"name0"}]";
        List userList = JSON.parseArray(json, User.class);

    }
}

json转换jsonobj直接获取属性

//定义一个json格式的字符串
String message = "{"code":1,"data":{"id":1001,"name":"lisi"}}";
//将字符串转换成json
JSONObject jsonObject = JSONObject.parseObject(message);
//取出data里的数据
String code = jsonObject.getString("code");
String data = jsonObject.getString("data");
 
System.out.println(code); //输出结果为:1
System.out.println(data); //输出结果为:{"name":"lisi","id":1001}
hutool转换

百度吧 其实跟fastjson用法差别不大

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936993.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号