• 发送GET请求:
  • //设置请求头
    HttpHeaders headers = new HttpHeaders(); headers.add("token",PostUtils.getToken()); //调用接口所需token,如果项目中没加权限拦截可以不需要这个token设置
    //请求体 HttpEntity
    <String> requestEntity = new HttpEntity<>(null, headers);
    //发起请求 RestTemplate restTemplate
    =new RestTemplate(); ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.exchange("调用的接口地址", HttpMethod.GET, requestEntity,JSONObject.class);
    //将拿到的数据转换成自己想要的格式 ResponseLockList responseLockList
    =JSON.parseObject(jsonObjectResponseEntity.getBody().toString(), new TypeReference<ResponseLockList>() {}); 
  • 发送POST请求:
  • //入参
    JSONObject jsonObj=null;
    //设置请求头
    HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); //请求的入参方式是json headers.add("token", getToken()); //调用接口所需token,如果项目中没有权限拦截可以不需要这个token设置
    //请求体 HttpEntity
    <String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
    //发送请求 RestTemplate restTemplate
    = new RestTemplate();
    //返回的json字符串 String json
    =restTemplate.postForObject("调用的接口地址", formEntity, String.class);
    //将json字符串转换成对象 ResponseSaasDel pwd
    =JSON.parseObject(json, new TypeReference<ResponseSaasDel>() {});
  • 参考:https://blog.csdn.net/likekobe2012/article/details/82663725
01-08 16:36