1
RestTemplate共有四类方法:
代码实例(四个controller方法对应以上四个方法),CommonResult<>类和Payment类是我写的Vo和JavaBean
@RestController public class OrderController { public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE"; @Resource private RestTemplate restTemplate; @GetMapping("/consumer/payment/create") public CommonResult<Payment> postForObject(Payment payment) { return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class); } @GetMapping("/consumer/payment/get/{id}") public CommonResult<Payment> getForObject(@PathVariable("id") Long id) { return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class,id); } @GetMapping("/consumer/payment/getForEntity/{id}") public CommonResult<Payment> getForEntity(@PathVariable("id") Long id) { ResponseEntity<CommonResult> res = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class); // 如果请求成功,返回内容 if (res.getStatusCode().is2xxSuccessful()) { return res.getBody(); } else { return new CommonResult<>(444, "操作失败"); } } @GetMapping("/consumer/payment/postForEntity") public CommonResult<Payment> postForEntity(Payment payment) { ResponseEntity<CommonResult> res = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class); if (res.getStatusCode().is2xxSuccessful()) { return res.getBody(); } else { return new CommonResult<>(444, "操作失败"); } } }