一、概述
RestTemplate是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。
RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。
传统情况下在java代码里访问Restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太繁琐。
Spring提供了一种简单便捷的模板类RestTemplate来进行操作:
java
@Component
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
java
@RestController
public class RestConsumer {
public static final String PAYMENT_URL = "http://localhost:8081";
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consumer/{id}")
public String getForObject(@PathVariable("id") Integer id){
return restTemplate.getForObject(PAYMENT_URL+"/provider/{id}",String.class, id);
}
}
java
@RestController
public class RestProvider {
@GetMapping("/provider/{id}")
public String getForObject(@PathVariable("id") Integer id){
return "provicer-"+id;
}
}
二、经典博客详解
RestTemplate详解
https://wenpingzhe.blog.csdn.net/article/details/121196840