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;
}
推荐阅读
-
基于RestTemplate的使用方法(详解)
-
基于RestTemplate的使用方法(详解)
-
Eureka restTemplate访问超时
-
用RestTemplate调取接口,取得返回数据,携带header,动态拼接url ,动态参数
-
@FeignClient 情况下header的传递方法,RestTemplate情况下Header传递方法
-
spring boot项目配置RestTemplate超时时长
-
java分布式基于RestTemplate的使用方法
-
RestTemplate的使用和原理你都烂熟于胸了吗?【享学Spring MVC】
-
为何一个@LoadBalanced注解就能让RestTemplate拥有负载均衡的能力?【享学Spring Cloud】
-
RestTemplate相关组件:ClientHttpRequestInterceptor【享学Spring MVC】