定制化开发网络接口返回的是json定制化开发格式的数据,用字符串接收,然后利用工具来将其转换为json或实体类。
1、创建跟json对象有相同属性的类
//json对象为{ "refresh_token": "xxx", "expires_in": 2592000, "scope": "xxx", "session_key": "xxx", "access_token": "xxx", "session_secret": "xxx"}//创建对应的java类@Datapublic class AuthVo { private String refreshToken; private String expiresIn; private String scope; private String sessionKey; private String accessToken; private String sessionSecret;}//请求的地址String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxx&client_secret=xxx";//HttpRequest为hutool的类import cn.hutool.http.HttpRequest;String body = HttpRequest.post(url).execute().body();//转换为对应的类, JSONUtil为import cn.hutool.json.JSONUtil;AuthVo authVo = JSONUtil.toBean(body,AuthVo.class);//查看属性System.out.println(authVo.getAccessToken());
2、直接转为json对象
//请求的地址String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxx&client_secret=xxx";String body = HttpRequest.post(url).execute().body();//直接转成json对象JSONObject jsonObject = new JSONObject(body);jsonObject.getStr("access_token")
发送参数
请求网络时需要带参数请求
直接在地址后面添加键值对
//拼凑链接字符串String authHost = "https://aip.baidubce.com/oauth/2.0/token?";String getAccessTokenUrl = authHost + "grant_type=client_credentials" + "&client_id=" + "xxx" + "&client_secret=" + "xxx";String body = HttpRequest.post(url).execute().body();//也可以设置带头部的请求String body2 = HttpRequest.post(url) .header("Tracking-Api-Key","a5f0febe-fb63-4f76-98ba-d2c7b4923773") .header("Content-Type ","application/json; charset=UTF-8") .execute() .body();
2,生成json格式的字符串传递不过好像也是转换成String再去请求,还在研究
相关资源: