-
1.简介:(百度)
RestTemplate是一个从Spring3.0开始支持的HTTP请求工具,它提供了常见的REST请求方案的模板,例如GET请求、POST请求、PUT请求、DELETE请求以及一些通用的请求执行方法,如exchange和execute。RestTemplate继承自InterceptingHttpAccessor并且实现了RestOperations接口,其中RestOperations接口定义了基本的RESTful操作,这些操作在RestTemplate中都得到了实现。
RestTemplate是Spring框架提供的一个同步Web Http客户端请求模板工具,用于简化访问Http服务的过程,降低了开发难度并增加了效率。然而,在Spring的新版本中,官方已经不建议使用RestTemplate了,而是推荐使用WebClient,因为WebClient提供了更强大的功能和更好的性能。尽管如此,RestTemplate仍然是一个非常有用的工具,特别是在需要快速构建REST客户端时。
2.一些个人理解
- 它能够解决服务之间调用的问题
-
Spring提供的通用的HTTP调用客户端,底层基于 HttpUrlConnection 或者 HttpComponents 等 http 连接工具实现.方便通过RestTemplate 向其他服务发起 HTTP 通用的方法( GET POST PUT DELETE...)调用服务间通信
3.如何使用RestTemplate
-
RestTemplate 包含在 org.springframework.web 包中,我们无需添加其他依赖 只需添加 spring-boot-starter-web依赖,如果已经添加,pom无需修改,直接使用 RestTemplate
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.通过配置类 @Bean 创建 RestTemplate@Bean 通过配置的方式创建bean,并且把bean放入spring的ioc容器,方便后续代码通过注入的方式使用
@Configuration
public class RestTemplateConfiguration {
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
}
3.它可以实现的功能包括:错误处理,消息转换,拦截器, 可以配置 网络连接相关的 超时时间
4.通过测试类验证调用外部接口 www.baidu.com 通过日志观察返回结果
@Test
public void testRestTemplate(){
ResponseEntity<String> forEntity =
restTemplate.getForEntity("https://www.baidu.com", String.class);
System.out.println(forEntity.getStatusCode());
System.out.println(forEntity.getBody());
}