hutool方式
准备
- 导入依赖alibaba(注意hutool也有json转化的api,但此演示的
JSONObject
则使用阿里巴巴的依赖)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
演示
- 通过第三方传过来的
ticket
,调用接口文档中的接口httpRequest
url,获取对应返回参数 - 请求若要指定
请求头参数
则新建一个 Map<String, String> headers = new HashMap<>();
存放各请求头参数, 放入以下代码http请求httpRequest.contentType("application/json").addHeaders(headers).xxxxxxxx().xxxx()
完成新增
private static final String userEndpoint = "http://xxxxxx:端口";
private HttpRequest initUserReq(String api){
String token = getAccessToken(userEndpoint);
if (Objects.isNull(token)){
throw new BizException("初始化请求失败");
}
return HttpUtil.createPost(userEndpoint + api+"?"
+"accessToken="+token);
}
private static final String VALIDA_TICKET="/xxx/xxx";
public EduYunUserInfo validaTicket(String ticket){
HttpRequest httpRequest = initUserReq(VALIDA_TICKET);
//整合请求接口所需参数
HashMap<String, Object> map = new HashMap<>();
map.put("ticket",ticket);
String request = JSONObject.toJSONString(map);
//请求第三方接口
String body = httpRequest.contentType("application/json").body(request).execute().body();
log.info("返回的应答报文{}",body);
JSONObject jsonObject = JSONObject.parseObject(body);
String code = jsonObject.getString("retCode");
if (!code.equals(SUCCESS)){
log.info("验证ticket失败,code:{}",code);
return null;
}
//将返回数据强转成我们自定义实体类(属性名要对应)
JSONObject data = jsonObject.getJSONObject("data");
EduYunUserInfo eduYunUserInfo = data.toJavaObject(EduYunUserInfo.class);
return eduYunUserInfo;
}
RestTemplate方式
private static final String userEndpoint = "http://xxxxxx:端口号";
private static final String LOGIN_API=userEndpoint+"/xxxx/xxxxx";
public R<UserLoginNewResp> getCurrentUser(UserLoginReq req) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(LOGIN_API, req, String.class);
String body = stringResponseEntity.getBody();
log.info("返回的应答报文{}",body);
if (StringUtils.isBlank(body)){
return R.failed("找不到用户数据");
}
JSONObject jsonObject = JSONObject.parseObject(body);
Integer code = (Integer) jsonObject.get("code");
if (code!=0){
return R.failed((String) jsonObject.get("msg"));
}
JSONObject entity = jsonObject.getJSONObject("entity");
UserLoginNewResp userLoginNewResp = entity.toJavaObject(UserLoginNewResp.class);
return R.ok(userLoginNewResp);
}
json对象字符串 转 map
- import com.fasterxml.jackson.databind.ObjectMapper;
- 模拟数据
@Test
public void test() throws IOException {
ObjectMapper MAPPER = new ObjectMapper();
String testA = "{\"result\":{\"Status\":1,\"Isp\":\"中国移动\"},\"code\":\"0\"}";
Map map = null;
map = MAPPER.readValue(testA, Map.class);
System.out.println(map.get("code").toString());
Integer a = (Integer) ((Map) map.get("result")).get("Status");
System.out.println(a);
}