Spring 框架中 ​​RestTemplate 的使用方法​​ - 实践

news/2025/10/2 10:33:08/文章来源:https://www.cnblogs.com/wzzkaifa/p/19123302

当然可以!下面我将为你详细讲解 Spring 框架中 ​​RestTemplate 的使用方法​​,包括它的基本概念、核心功能、常见用法、配置方式、以及在实际项目中的最佳实践,并附带代码示例,帮助你全面掌握。


一、什么是 RestTemplate?

​RestTemplate​​ 是 Spring Framework 提供的一个用于访问 RESTful 服务的同步客户端工具类,它是对 HTTP 客户端的一层封装,简化了与 REST 服务交互的过程,比如:

  • 发送 GET、POST、PUT、DELETE 请求

  • 设置请求头、请求参数、请求体

  • 处理响应数据(JSON / XML 等)

  • 错误处理

它适用于 ​​服务与服务之间(如微服务架构)的 HTTP 通信​​,在 Spring Boot 2.x 之前非常常用。但从 ​​Spring 5 开始,官方推荐使用 WebClient(响应式非阻塞)作为 RestTemplate 的替代方案​​,不过 ​​RestTemplate 仍然被广泛使用,特别是在传统 Spring MVC 项目中​​。


二、RestTemplate 的核心特点

特性

说明

同步阻塞

RestTemplate 是 ​​同步、阻塞式​​ 的 HTTP 客户端,调用线程会等待响应返回

支持多种 HTTP 方法

GET、POST、PUT、DELETE、PATCH 等

支持请求/响应的序列化与反序列化

比如自动将 Java 对象转为 JSON 发送,或者将返回的 JSON 转为 Java 对象

灵活的请求构造

可以设置 URL、请求头、请求参数、请求体等

支持多种响应处理方式

比如直接获取字符串、字节数组、对象等

易于使用

相比原生 HttpURLConnection 或 HttpClient,使用更简单


三、RestTemplate 的基本使用步骤

步骤 1:引入依赖(Spring Boot 项目中通常已包含)

如果你使用的是 Spring Boot,一般无需额外引入,因为 spring-web已经包含 RestTemplate(在 spring-boot-starter-web 中)。

但如果你想自定义或明确引入,可以检查你的 pom.xml是否有以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

⚠️ 注意:从 Spring Boot 2.7 开始,RestTemplate 不再自动配置,你需要手动创建 Bean;Spring Boot 3.x 推荐使用 WebClient。

步骤 2:创建 RestTemplate 实例

方式一:直接 new(不推荐,无连接池等优化)

RestTemplate restTemplate = new RestTemplate();

方式二:通过 Spring Bean 方式注入(推荐)

你可以在配置类中定义一个 RestTemplate Bean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}
}

然后就可以通过 ​​@Autowired​​ 注入使用:

@Autowired
private RestTemplate restTemplate;

步骤 3:使用 RestTemplate 发送请求

下面介绍最常用的几种 HTTP 方法的使用。


1. GET 请求

① 获取字符串响应
String url = "https://jsonplaceholder.typicode.com/posts/1";
String result = restTemplate.getForObject(url, String.class);
System.out.println(result);
② 获取对象(自动反序列化 JSON 到 Java 对象)

假设有一个类:

public class Post {private Integer userId;private Integer id;private String title;private String body;// getters / setters ...
}

调用:

String url = "https://jsonplaceholder.typicode.com/posts/1";
Post post = restTemplate.getForObject(url, Post.class);
System.out.println(post.getTitle());
③ 带路径参数的 GET 请求
String url = "https://jsonplaceholder.typicode.com/posts/{id}";
Map params = new HashMap<>();
params.put("id", 1);
Post post = restTemplate.getForObject(url, Post.class, params);
// 或者
Post post = restTemplate.getForObject(url, Post.class, 1); // 直接传参
④ 带请求头的 GET 请求

需要使用 HttpHeaders和 HttpEntityRestTemplate.exchange()

String url = "https://jsonplaceholder.typicode.com/posts/1";
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer your_token_here");
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity entity = new HttpEntity<>(headers);
ResponseEntity response = restTemplate.exchange(url,HttpMethod.GET,entity,Post.class
);
Post post = response.getBody();
System.out.println(post.getTitle());

2. POST 请求

① 发送对象并接收对象(常用)
String url = "https://jsonplaceholder.typicode.com/posts";
Post newPost = new Post();
newPost.setTitle("Hello");
newPost.setBody("This is a test post");
// userId 可以根据 API 要求设置
Post createdPost = restTemplate.postForObject(url, newPost, Post.class);
System.out.println(createdPost.getId());
② 带请求头的 POST 请求
String url = "https://example.com/api/posts";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer xxxx");
Post newPost = new Post();
newPost.setTitle("Hello");
newPost.setBody("Content");
HttpEntity requestEntity = new HttpEntity<>(newPost, headers);
ResponseEntity response = restTemplate.exchange(url,HttpMethod.POST,requestEntity,Post.class
);
Post result = response.getBody();

3. PUT 请求(更新资源)

String url = "https://jsonplaceholder.typicode.com/posts/1";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Post updatedPost = new Post();
updatedPost.setId(1);
updatedPost.setTitle("Updated Title");
updatedPost.setBody("Updated Body");
HttpEntity requestEntity = new HttpEntity<>(updatedPost, headers);
restTemplate.exchange(url, HttpMethod.PUT, requestEntity, Void.class);
// 如果你不需要返回值,可以用 Void.class

4. DELETE 请求

String url = "https://jsonplaceholder.typicode.com/posts/1";
restTemplate.delete(url);

如果带路径参数:

String url = "https://jsonplaceholder.typicode.com/posts/{id}";
Map params = Collections.singletonMap("id", 1);
restTemplate.delete(url, params);

四、RestTemplate 的高级用法

1. 使用 exchange() 方法(最灵活)

exchange()是 RestTemplate 最强大的方法,支持所有 HTTP 方法,可以自定义请求头、请求体,且能获取完整的响应信息(状态码、响应头、响应体)。

ResponseEntity response = restTemplate.exchange(url,                    // 请求URLHttpMethod.GET,         // 请求方法entity,                 // 请求实体(可含headers、body)Post.class              // 响应体类型
);
HttpStatus statusCode = response.getStatusCode();      // 如 HttpStatus.OK
HttpHeaders responseHeaders = response.getHeaders();   // 响应头
Post responseBody = response.getBody();                // 响应体

2. 使用 ResponseEntity 接收更丰富的响应信息

ResponseEntity response = restTemplate.getForEntity(url, String.class);
System.out.println(response.getStatusCode()); // 如 200 OK
System.out.println(response.getBody());

3. 错误处理

默认情况下,如果服务端返回 4xx 或 5xx,RestTemplate 会抛出异常,比如:

  • HttpClientErrorException(4xx)

  • HttpServerErrorException(5xx)

你可以捕获这些异常做处理:

try {Post post = restTemplate.getForObject(url, Post.class);
} catch (HttpClientErrorException e) {System.err.println("客户端错误: " + e.getStatusCode() + ", " + e.getResponseBodyAsString());
} catch (HttpServerErrorException e) {System.err.println("服务端错误: " + e.getStatusCode());
} catch (RestClientException e) {System.err.println("Rest请求异常: " + e.getMessage());
}

五、RestTemplate 的配置(可选)

你可以通过自定义 RestTemplate的构建过程,配置例如:

  • 消息转换器(如支持 JSON、XML)

  • 拦截器(添加统一 Header、日志等)

  • 超时设置(需要使用 HttpComponentsClientHttpRequestFactory 或 SimpleClientHttpRequestFactory)

示例:配置超时和拦截器

@Bean
public RestTemplate restTemplate() {RestTemplate restTemplate = new RestTemplate();// 设置请求工厂(可配置超时)SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setConnectTimeout(5000); // 连接超时时间 msfactory.setReadTimeout(5000);    // 读取超时时间 msrestTemplate.setRequestFactory(factory);// 添加拦截器(比如统一加 Token)restTemplate.getInterceptors().add((request, body, execution) -> {request.getHeaders().add("Authorization", "Bearer xxx");return execution.execute(request, body);});return restTemplate;
}

⚠️ 如果你要更高级的 HTTP 客户端功能(如连接池、更灵活的超时控制),可以考虑使用 ​​Apache HttpClient​​ 或 ​​OkHttp​​ 作为底层实现,然后传入对应的 ClientHttpRequestFactory

六、RestTemplate vs WebClient

对比项

RestTemplate

WebClient

类型

同步阻塞

异步非阻塞(响应式)

适用场景

传统 MVC、简单调用

高并发、响应式编程、WebFlux

是否推荐新项目使用

❌ 不推荐(尤其 Spring 6 / Boot 3)

✅ 推荐

学习曲线

简单

较复杂(需了解 Reactor)

Spring Boot 3 支持

已移除自动配置

✅ 官方主推

如果你使用的是 ​​Spring Boot 3+ 或 Spring 6+,官方已移除 RestTemplate 自动配置,推荐使用 WebClient​​。


七、总结:RestTemplate 使用要点

项目

说明

作用

用于同步调用 RESTful API,简化 HTTP 客户端操作

推荐使用场景

传统 Spring MVC 项目,简单 HTTP 调用

创建方式

推荐通过 @Bean 方式注入

常用方法

getForObject、postForObject、exchange、delete 等

请求构造

支持 URL、参数、Header、Body

响应处理

支持 String、JSON 对象、ResponseEntity 等

错误处理

捕获 HttpClientErrorException / HttpServerErrorException

配置优化

可配置超时、拦截器、消息转换器等

替代方案

WebClient(响应式,Spring 5+ 推荐)


八、附:完整示例代码(GET + POST)

@Service
public class ApiService {@Autowiredprivate RestTemplate restTemplate;// GET 示例public Post getPostById(int id) {String url = "https://jsonplaceholder.typicode.com/posts/{id}";return restTemplate.getForObject(url, Post.class, id);}// POST 示例public Post createPost(Post newPost) {String url = "https://jsonplaceholder.typicode.com/posts";return restTemplate.postForObject(url, newPost, Post.class);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/924793.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

桂林新站优化网站模板后台怎么做

输入一个英文句子&#xff0c;翻转句子中单词的顺序&#xff0c;但单词内字符的顺序不变。为简单起见&#xff0c;标点符号和普通字母一样处理。例如输入字符串"I am a student. "&#xff0c;则输出"student. a am I"。 示例 1&#xff1a; 输入: "…

tnkstat3e-merge-0

统计思维(程序员的概率统计)第三版(一)原文:allendowney.github.io/ThinkStats/index.html 译者:飞龙 协议:CC BY-NC-SA 4.0统计思维第三版原文:allendowney.github.io/ThinkStats/index.htmlThink Stats 是面…

如何用pivotby函数实现数据透视(1)

背景 ========================================================================================= 因为每次都要统计当前毕业的毕业去向落实率,每次都在拉两次透视表,做N次VLOOPUP,再写一个求百分比的公式, ---…

网站建设 拖欠尾款水果建设网站前的市场分析

指针初阶 1.指针是什么2.指针和指针类型2.1 指针-整数2.2 指针的解引用 3.野指针3.1 野指针成因3.2如何避免野指针 4.指针运算4.1 指针-整数4.2 指针-指针4.3 指针的关系运算 5.指针和数组6.二级指针7.指针数组 1.指针是什么 指针是什么&#xff1f; 指针理解的2个要点&#xf…

JavaScript零基础入门速通(完整) - 指南

JavaScript零基础入门速通(完整) - 指南pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Mo…

企业为什么做平台网站企业网站建设的实验报告

准备工作 这部分其实在谷歌或者百度上搜索下就可以完成的&#xff0c;可是我就是想再啰嗦一遍&#xff0c;说不定有比我更懒的同学呢哈哈~ 第一步 Python的安装配置 打开官网: https://www.python.org/downloads/ 目前官网上已经更新到3.6.1啦&#xff08;这更新速度我是服的&…

完整教程:Nginx反向代理核心原理揭秘

完整教程:Nginx反向代理核心原理揭秘pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Mona…

详细介绍:五大关系数据库(sqlserver、mysql、oracle、pgsql、sqlite)的对象名称和转义字符

详细介绍:五大关系数据库(sqlserver、mysql、oracle、pgsql、sqlite)的对象名称和转义字符2025-10-02 10:17 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !importa…

@RequestParam 什么时候可以省略?

参数名一致时 当HTTP请求中的参数名与控制器方法参数名完全一致时,@RequestParam可省略。 非必需参数 当请求参数为非必需(即允许未传递该参数时),可通过设置@RequestParam(required=false)或省略注解,此时即使未…

做全景效果图的网站wordpress适应ie6

《“爱读书”--给你讲技术》&#xff0c;我来看书&#xff0c;你来进步&#xff0c;让我们开始吧&#xff01;本书简介书名为《轻量级JavaEE企业应用实战》&#xff0c;是本人在学习JavaEE框架的时候阅读的第一本书&#xff0c;本书对于框架及相关基础知识讲述的比较详细和浅显…

段页式管理方式

分段分页管理中最大的优缺点优点 缺点分页管理 内存空间利用率高,不会产生外部碎片,只会有少量的页内碎片 不方便按照逻辑模块实现信息的共享和保护分段管理 很方便按照逻辑模块实现信息的共享和保护 如果段长过大,…

网站建设与单位干部作风的关系网站竞价推广都有哪些

有些粉丝&#xff0c;希望对自定义业务中&#xff0c;驳回到发起人进行处理&#xff0c;比如可以重新进行发起流程&#xff0c;下面就给出一种方式&#xff0c;当然不一定是最好的方式&#xff0c;只是提供一种参考而已&#xff0c;以后可以考虑动态根据流程状态或节点信息进行…

推进电子设计革新:为什么模拟仿真正是核心助力?

在高速发展的电子设计领域,模拟仿真已成为现代工程师的「得力助手」,它不仅能快速验证设计,还能显著提升流程效率与质量。1、仿真的三大优势:提前预见,精准优化,高效迭代 错误无处遁形 仿真能在设计实施前及时暴…

河北网站seo策划公司变更地址需要多少钱

T2-简单 MST题解 题意 设 ω ( x ) \omega(x) ω(x)为 x x x的质因数所构成的集合大小&#xff1b; 给两个正整数 l l l r r r&#xff0c;图上有 r − l 1 r-l1 r−l1个点&#xff0c;为 l , l 1 , l 2 , ⋯ , r − 2 , r − 1 , r l,l1,l2,\cdots,r-2,r-1,r l,l1,l2,…

网站域名 格式怎么做学校网站和微信公众号

日常工作中&#xff0c;经常会用到FTP&#xff0c;一般情况下&#xff0c;FTP站点在IE中&#xff08;尤其是IE7以后版本&#xff09;打开&#xff0c;默认都不是以文件夹视图方式打开的&#xff0c;这时IE也会给你提示“若要在 Windows 资源管理器中查看此 FTP 站点&#xff0c…

完整教程:深度解析ZStack Cloud v5.4.0 LTS 基础架构三大核心突破

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

深入解析:精读C++20设计模式:结构型设计模式:装饰器模式

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

*和 内存和地址 实例代码

#include <bits/stdc++.h> using namespace std; int main(){int number=42;int *ptr=&number;//ptr 存储 number 的地址 cout<<"变量值:"<<number<<endl; //42cout&l…

应用安全 --- 安卓加固 之 IPC

应用安全 --- 安卓加固 之 IPC应用安全 --- 安卓加固 之 IPC 会有一个调用者和被调用者,我们frida只能hook其中一个,无法获取全貌### 为什么看不到真实调用者信息?核心原因 :你看到的是一个 Binder IPC跨进程调用…

深入解析:前端开发,iframe 相关经验总结

深入解析:前端开发,iframe 相关经验总结pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "…