Java教程

Ribbon RestTemplate 的使用方法

本文主要是介绍Ribbon RestTemplate 的使用方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1

要想使用RestTemplate,需要添加配置类,注入bean

RestTemplate共有四类方法

  • getForObject(url, class)
    发送get请求,返回值为class
  • postForObject(url, javabean, class)
    发送post请求,请求参数是JavaBean,返回值为class
  • getForEntity(url, class)
    发送get请求,返回包装过的class
  • postForEntity(url, javabean, class)
    发送post请求, 请求参数是JavaBean,返回包装过的class

代码实例(四个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, "操作失败");
        }
    }
}
这篇关于Ribbon RestTemplate 的使用方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!