RestTemplate简介
Spring's central class for synchronous client-side HTTP access.
It simplifies communication with HTTP servers, and enforces RESTful principles.
It handles HTTP connections, leaving application code to provide URLs(with possible template variables) and extract results.
上面这段是RestTemplate类中的简单介绍,RestTemplate是Spring3.0后开始提供的用于访问 Rest 服务的轻量级客户端,相较于传统的HttpURLConnection、Apache HttpClient、OkHttp等框架,RestTemplate大大简化了发起HTTP请求以及处理响应的过程。本文关注RestTemplate是如何使用的,暂不涉及内部的实现原理。
RestTemplate支持多种的请求方式,具体参考下表:
HTTP method | RestTemplate methods |
---|---|
GET | getForObject、getForEntity |
POST | postForObject、postForEntity、postForLocation |
PUT | put |
DELETE | delete |
HEAD | headForHeaders |
OPTIONS | optionsForAllow |
PATCH | patchForObject |
any | exchange、execute |
引入RestTemplate
- 方式一,使用无参构造器直接new一个对象
private RestTemplate restTemplate = new RestTemplate();
- 方式二,先注册成Spring的Bean对象,之后使用的时候直接注入
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
测试准备
新建User对象,用于下面不同请求方式的测试。
@Data
public class User {
/**
* id
*/
private Long id;
/**
* 用户名
*/
private String username;
/**
* 年龄
*/
private Integer age;
}
GET请求
GET请求对应两个方法,getForObject()和getForEntity(),每个方法又对应有具体的三个重载方法。这两者的区别在于getForObject()返回的是一个简单的对象,而getForEntity()响应的数据中,还额外包含有与HTTP相关的信息,如响应码、响应头等。
/**
* GET资源 (发送一个HTTP GET请求,返回的请求体将映射为一个对象)
* <p>
* 1. 执行根据URL检索资源的GET请求
* 2. 根据responseType参数匹配为一定的类型
* 3. getForObject()只返回所请求类型的对象信息
*/
@Test
public void getForObject() {
long id = 0;
//URL中的{id}占位符最终将会用方法的id参数来填充
String url = "http://localhost:9000/user/{id}";
//重载1:最后一个参数是大小可变的参数列表ÿ