【笔记】SpringBoot项目整合RestTemplate

前言

SpringBoot项目整合RestTemplate,实现发送请求

添加依赖

pom.xml
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>

GET请求

url:请求地址
Object.class:响应数据的类型,可以封装实体类作为响应数据的类型

1
restTemplate.getForObject(url, Object.class);

通过字符串拼接传递参数

{num}:在URL地址后拼接占位符,占位符用一组大括号数字编号组成,从方法第3个参数开始为请求的第1个参数值
Object.class:响应数据的类型,可以封装实体类作为响应数据的类型

1
2
3
String url = ""

restTemplate.getForObject(url + "?key={1}&key={2}", Object.class, "value", "value");

通过Map传递参数

{name}:在URL地址后拼接占位符,占位符用一组大括号键名组成,从方法第3个参数开始为请求的第1个参数值
Object.class:响应数据的类型,可以封装实体类作为响应数据的类型

1
2
3
4
5
String url = ""
Map<String, Object> param = new HashMap<>();
param.put("key", "value");

restTemplate.getForObject(url, Object.class, param);

POST请求

通过Map传递参数

  • 只能使用LinkedMultiValueMap()

Object.class:响应数据的类型,可以封装实体类作为响应数据的类型

1
2
3
4
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("key", "value");

restTemplate.postForObject(url, param, Object.class);

通过自定义类传递参数

1
2
3
4
5
6
7
8
9
10
11
class Body {
String key;

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}
}
1
2
3
4
Body body = new Body();
body.setKey("value");

restTemplate.postForObject(url, body, Object.class);

通过HttpEntity传递参数

  • 可以设置请求头

有请求参数

1
2
3
4
5
6
// 设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/json"));
httpHeaders.add("key", "value");

restTemplate.postForObject(url, new HttpEntity<>(param, httpHeaders), Object.class);

无请求参数

1
2
3
4
5
6
// 设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/json"));
httpHeaders.add("key", "value");

restTemplate.postForObject(url, new HttpEntity<>(httpHeaders), Object.class);

exchange方法

1
2
3
4
HttpHeaders headers = new HttpHeaders();

Map param = new HashMap();
param.put("key", "value");

GET请求

1
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), Object.class);

POST请求

有请求参数

1
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(param, headers), Object.class);

无请求参数

1
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(headers), Object.class);

获取响应体

1
Object responseBody = responseEntity.getBody();

URL编码

1
String url = URLEncoder.encode("", "UTF-8");

完成

参考文献

简书——程序员小杰
CSDN——自傷無色丶
CSDN——L-960