欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

restTemplate

程序员文章站 2022-03-02 17:16:43
...

/**

  • json转换类
    */
    private static final Gson GSON = (new GsonBuilder()).create();

1、发送get请求

    public UicUser getUicUser(String phone) {
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<String> responseEntity = restTemplate.getForEntity(Constants.TEST_UIC_USER + "?phone=" + phone, String.class);
                boolean isExist = responseEntity.getStatusCode() == org.springframework.http.HttpStatus.OK && responseEntity.getBody() != null;
                return isExist ? GSON.fromJson(responseEntity.getBody(), UicUser.class) : null;
    }

2、发送post请求

            @PostMapping("data")
            @ResponseBody
            public JsonEntity synchroData(@RequestBody SynchroData synchroData) {
                boolean result = false;
                RestTemplate restTemplate = new RestTemplate();
                Temp temp = new Temp(synchroData.getAreaId(), synchroData.getCode());
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(Constants.URL, new HttpEntity<>(GSON.toJson(temp), headers), String.class);
                if (responseEntity.getStatusCode() == org.springframework.http.HttpStatus.OK) {
                            ResponseVo responseVo = GSON.fromJson(responseEntity.getBody(), ResponseVo.class);
                  if ("0".equals(responseVo.getRetCode())) {//retCode标识请求返回参数成功(公司内部定义的)
                        result = initService.addSourceData(responseVo.getResponse(), synchroData);
                  }
              }
                return ReturnUtil.success(result);
    }

3、post2

            public UicUser getUicUser(String phone) {
                    RestTemplate restTemplate = new RestTemplate();
                    ResponseEntity<String> responseEntity = restTemplate.getForEntity(Constants.UIC_USER + "?phone=" + phone, String.class);
                    boolean isExist = responseEntity.getStatusCode() == org.springframework.http.HttpStatus.OK && responseEntity.getBody() != null;
                    return isExist ? GSON.fromJson(responseEntity.getBody(), UicUser.class) : null;
}