抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

摘要:无。

环境

Windows 10 企业版 LTSC 21H2
Java 1.8
Tomcat 8.5.50
Maven 3.6.3
Spring 5.3.31

1 概述

在分布式系统中,一个应用经常需要调用其他服务暴露的HTTP接口,这就是远程调用。与单体应用内的直接方法调用不同,远程调用要处理网络传输、请求构建、序列化、响应解析、超时控制等一系列问题。

RestTemplate封装了底层的连接管理与消息转换,用一组简洁的方法即可完成大多数HTTP调用。

2 常用方法

常用方法:

  • getForObject:GET请求,返回响应体。
  • getForEntity:GET请求,返回ResponseEntity类型的完整响应。
  • postForObject:POST请求,返回响应体。
  • postForEntity:POST请求,返回ResponseEntity类型的完整响应。
  • put:PUT请求,无返回值。
  • delete:DELETE请求,无返回值。
  • exchange:通用方法,接收HttpMethod参数,返回ResponseEntity类型的完整响应。

3 配置方式

3.1 半注解配置

在spring-mvc.xml配置文件中注册RestTemplate对象:

spring-mvc.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 启用对象扫描 -->
<context:component-scan base-package="com.example.controller"/>

<!-- 启用注解驱动 -->
<mvc:annotation-driven/>

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>

<!-- 注册RestTemplate对象 -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
</beans>

3.2 全注解配置

在配置类中注册RestTemplate对象:

java
1
2
3
4
5
6
7
@Configuration
public class DemoConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

4 基本用法

以下示例假设被调用方提供了若干REST接口,调用方通过注入的RestTemplate发起请求。

4.1 GET请求

4.1.1 简单使用

获取响应体:

java
1
User user = restTemplate.getForObject("http://localhost:8080/user/1", User.class);

4.1.2 路径变量

URL中的动态部分可以用{占位符}表示,通过可变参数或Map传入实际值,占位符对应实际值的顺序或名称必须一致。

使用可变参数传值:

java
1
User user = restTemplate.getForObject("http://localhost:8080/user/{id}", User.class, 1L);

使用Map传值:

java
1
2
3
Map<String, Object> params = new HashMap<>();
params.put("id", 1L);
User user = restTemplate.getForObject("http://localhost:8080/user/{id}", User.class, params);

4.1.3 查询参数

查询参数拼接在URL中,同样可以用占位符填充:

java
1
List<User> userList = restTemplate.getForObject("http://localhost:8080/user?page={page}&size={size}", List.class, 1, 10);

4.2 POST请求

提交JSON请求体:

java
1
2
3
User param = new User();
param.setName("张三");
User user = restTemplate.postForObject("http://localhost:8080/user", param, User.class);

提交表单参数:

java
1
2
3
4
5
6
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.add("name", "张三");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);
User user = restTemplate.postForObject("http://localhost:8080/user/form", request, User.class);

4.3 PUT请求

执行更新操作:

java
1
2
3
User param = new User();
param.setName("李四");
restTemplate.put("http://localhost:8080/user/{id}", param, 1L);

4.4 DELETE请求

执行删除操作:

java
1
restTemplate.delete("http://localhost:8080/user/{id}", 1L);

4.5 通用方法

使用exchange()方法可以表达任意HTTP方法,并能同时设置请求头和请求体,是功能最全的入口:

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 请求参数
User param = new User();
param.setName("张三");
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// 组装请求体
HttpEntity<User> request = new HttpEntity<>(param, headers);
// 发送请求
ResponseEntity<User> response = restTemplate.exchange(
"http://localhost:8080/user/{id}",
HttpMethod.PUT,
request,
User.class,
1L
);
System.out.println("status: " + response.getStatusCode());
System.out.println("headers: " + response.getHeaders());
System.out.println("body: " + response.getBody());

5 进阶用法

5.1 超时配置

默认使用SimpleClientHttpRequestFactory不设置超时时间,网络异常时可能长时间阻塞,建议配置连接超时和读取超时。

如果需要连接池等更强的能力,可以换成HttpComponentsClientHttpRequestFactory工厂。

5.1.1 半注解配置

在spring-mvc.xml配置文件中配置带超时参数的请求工厂:

spring-mvc.xml
1
2
3
4
5
6
7
8
9
10
<!-- 配置请求工厂,设置连接超时和读取超时,单位毫秒 -->
<bean id="requestFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory">
<property name="connectTimeout" value="3000"/>
<property name="readTimeout" value="5000"/>
</bean>

<!-- 注册RestTemplate对象,通过构造器注入请求工厂 -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="requestFactory"/>
</bean>

5.1.2 全注解配置

在配置类中通过SimpleClientHttpRequestFactory设置连接超时和读取超时:

java
1
2
3
4
5
6
7
8
9
10
@Configuration
public class DemoConfig {
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(3000); // 建立TCP连接的超时时间,单位毫秒
factory.setReadTimeout(5000); // 等待响应数据的超时时间,单位毫秒
return new RestTemplate(factory);
}
}

5.2 拦截器

通过ClientHttpRequestInterceptor可以在请求发出前和响应返回后统一处理,常用于统一鉴权等场景。

定义拦截器类:

java
1
2
3
4
5
6
7
8
public class DemoInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
// 为每个请求统一添加自定义请求头
request.getHeaders().add("X-Request-Source", "demo");
return execution.execute(request, body);
}
}

5.2.1 半注解配置

在spring-mvc.xml中注册拦截器:

spring-mvc.xml
1
2
3
4
5
6
7
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="interceptors">
<list>
<bean class="com.example.interceptor.DemoInterceptor"/>
</list>
</property>
</bean>

5.2.2 全注解配置

在配置类中注册拦截器:

java
1
2
3
4
5
6
7
8
9
@Configuration
public class DemoConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(new DemoInterceptor()));
return restTemplate;
}
}

评论