使用RestTemplate分别请求get和post的请求接口数据,get请求使用getForObject()方法,post请求使用postForObject()方法。接受数据之后用过json映射到实体类和集合中返回。
post请求数据接收
post接口
@PostMapping("/getAccountInfo")
public RestReturn<ThirdUserInfoDTO> getAccountInfo(@RequestBody @Validated LoginDTO loginDTO){
ThirdUserInfoDTO thirdUserInfoDTO = thirdService.getAccountInfo(loginDTO);
//判断用户是否存在,及获取所属组织信息
return new RestReturn().success(thirdUserInfoDTO, RestReturnEnum.SUCCESS.getMessage());
}
RestTemplate请求post接口数据,返回类型为ThirdUserInfoDTO对象
esultOrgListDTO> currentOrgs(LoginDTO loginDTO) {
//获取当前用户信息,loginDTO为请求参数,String.class为返回类型
String s = restTemplate.postForObject("http://10.136.88.94:8091/api/3rd/getAccountInfo", loginDTO, String.class);
JSONObject jsonObject = JSONObject.parseObject(s);
String data = jsonObject.getString("data");
//对象接受json数据
ThirdUserInfoDTO thirdUserInfoDTO= JSON.parseObject(jsonObject.getString("data"), new TypeReference<ThirdUserInfoDTO>(){});
if(ObjectUtils.isEmpty(thirdUserInfoDTO)){
throw new CustomException(RestReturnEnum.USERINFO_NOT_EXISTED);
}
List<ResultOrgListDTO> orgs = thirdUserInfoDTO.getOrgs();
return orgs;
}
get接口
@GetMapping("/nodeInfo/{orgId}")
public RestReturn<List<ThirdNodeInfoDTO>> nodeInfoByOrgId(@ApiParam(value = "组织id",required = true) @PathVariable("orgId") Long orgId){
//根据组织id获取节点信息
List<ThirdNodeInfoDTO> nodes = thirdService.nodeInfoByOrgId(orgId);
return new RestReturn().success(nodes, RestReturnEnum.SUCCESS.getMessage());
}
RestTemplate请求get接口数据,返回类型为List集合
@Override
public List<ThirdNodeInfoDTO> currentOrgNodes(Long orgId) {
List<ThirdNodeInfoDTO> list =new ArrayList<>();
String s = restTemplate.getForObject("http://10.136.88.94:8091/api/3rd/nodeInfo/{orgId}",String.class,orgId);
//拿到json对象数组
JSONArray jsonArray = JSONObject.parseObject(s).getJSONArray("data");
//循环将json对象数组放到对象中
jsonArray.forEach(x ->{
ThirdNodeInfoDTO thirdNodeInfoDTO =JSONObject.toJavaObject((JSON) x ,ThirdNodeInfoDTO.class);
if(thirdNodeInfoDTO!=null){
list.add(thirdNodeInfoDTO);
}
});
return list;
}