简介
在写项目于中我们经常需要调用远程和HTTP接口,Spring官方提供了RestTemple类,使我们发送HTTP请求更加便捷。
我们学习RestTemple之前我们看看官方文档是怎么描述的。Spring官方文档
Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others. RestTemplate offers templates for common scenarios by HTTP method, in addition to the generalized exchange and execute methods that support less frequent cases
RestTemplate是一个同步的HTTP请求客户端,通过在JDK的HttpURLConnection、Apache HttpComponents等底层HTTP客户端库上暴露简单的模板方法API,使得进行HTTP请求变得更加便捷。RestTemplate提供了按HTTP方法处理常见场景,此外,还提供了通用的exchange和execute方法,支持不太常见的使用情景。
环境配置
添加RestTemple的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
编写Spring配置类,注册将Bean注册到容器中
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
在需要使用RestTemple时注入RestTemple实例
@Autowired
private RestTemplate restTemplate;
基本使用
发送GET请求
要发起GET请求,可以使用getForObject()或getForEntity()方法。getForObject()方法将响应体作为对象返回,而getForEntity()方法返回完整的响应,包括头部信息和状态码。
// 发出 GET 请求并以字符串形式返回
String response = restTemplate.getForObject( "url" , String.class);
// 发出 GET 请求并返回整个响应对象
ResponseEntity<String> response =restTemplate.getForEntity( "url" , String.class);
发送POST 请求
要发出 POST 请求,您可以使用postForObject()或postForEntity()方法。这些方法的工作方式与 GET 方法类似,方法postForObject()将响应正文作为对象返回,方法postForEntity()返回整个响应。
// 发出 POST 请求并以字符串形式返回
String response = restTemplate.postForObject( "url" , new Post (), String.class);
// 发出 POST 请求并返回整个响应对象
ResponseEntity<String> response =restTemplate.postForEntity( "url" , new Post (), String.class);
发送 PUT 和 DELETE 请求
要发出 PUT 和 DELETE 请求,您可以分别使用put()和delete()方法。
// 发出 PUT 请求
restTemplate.put( "url" , new Post ());
// 发出 DELETE 请求
restTemplate.delete( "url" );