Spring Boot - Rest Template
Rest Template 用于创建消费 RESTful Web Services 的应用程序。您可以使用 exchange() 方法来消费所有 HTTP 方法的 web services。下面的代码展示了如何创建 Rest Template 的 Bean 以自动注入 Rest Template 对象。
...
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
GET
使用 RestTemplate 的 exchange() 方法消费 GET API
假设这个 URL http://localhost:8080/products 返回以下 JSON,我们将使用 Rest Template 消费这个 API 响应,代码如下 −
[
{
"id": "1",
"name": "Honey"
},
{
"id": "2",
"name": "Almond"
}
]
要消费该 API,您需要遵循以下步骤 −
自动注入 Rest Template 对象。
使用 HttpHeaders 设置请求头。
使用 HttpEntity 包装请求对象。
为 exchange() 方法提供 URL、HttpMethod 和返回类型。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@GetMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity <String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange("
http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
}
}
POST
使用 RestTemplate 的 exchange() 方法消费 POST API
假设这个 URL http://localhost:8080/products 返回以下响应,我们将使用 Rest Template 消费这个 API 响应。
下面的代码是请求体 −
{
"id":"3",
"name":"Ginger"
}
下面的代码是响应体 −
Product is created successfully
要消费该 API,您需要遵循以下步骤 −
自动注入 Rest Template 对象。
使用 HttpHeaders 设置请求头。
使用 HttpEntity 包装请求对象。在此,我们将 Product 对象包装以发送到请求体。
为 exchange() 方法提供 URL、HttpMethod 和返回类型。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@PostMapping(value = "/template/products")
public String createProducts(@RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
}
}
PUT
使用 RestTemplate 的 exchange() 方法消费 PUT API
假设这个 URL http://localhost:8080/products/3 返回以下响应,我们将使用 RestTemplate 来消费这个 API 响应。
下面的代码是 Request body −
{
"name":"Indian Ginger"
}
下面的代码是 Response body −
Product is updated successfully
要消费这个 API,您需要遵循以下要点 −
Autowired RestTemplate 对象。
使用 HttpHeaders 设置请求头。
使用 HttpEntity 包装请求对象。这里,我们将 Product 对象包装后发送到请求体中。
为 exchange() 方法提供 URL、HttpMethod 和返回类型。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@PutMapping(value = "/template/products/{id}")
public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
}
}
DELETE
使用 RestTemplate 的 exchange() 方法消费 DELETE API
假设这个 URL http://localhost:8080/products/3 返回以下响应,我们将使用 RestTemplate 来消费这个 API 响应。
下面显示的代码行是 Response body −
Product is deleted successfully
要消费这个 API,您需要遵循以下要点 −
Autowired RestTemplate 对象。
使用 HttpHeaders 设置请求头。
使用 HttpEntity 包装请求对象。
为 exchange() 方法提供 URL、HttpMethod 和返回类型。
...
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@DeleteMapping(value = "/template/products/{id}")
public String deleteProduct(@PathVariable("id") String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
}
}
示例 - Rest Template 的使用
完整的 Rest Template Controller 类文件如下所示 −
ConsumeWebService.java
package com..demo.controller;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com..demo.model.Product;
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@GetMapping(value = "/template/products")
public String getProductList() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange(
"http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
}
@PostMapping(value = "/template/products")
public String createProducts(@RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products", HttpMethod.POST, entity, String.class).getBody();
}
@PutMapping(value = "/template/products/{id}")
public String updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(product,headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.PUT, entity, String.class).getBody();
}
@DeleteMapping(value = "/template/products/{id}")
public String deleteProduct(@PathVariable("id") String id) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<Product> entity = new HttpEntity<Product>(headers);
return restTemplate.exchange(
"http://localhost:8080/products/"+id, HttpMethod.DELETE, entity, String.class).getBody();
}
}
作为 REST 服务,我们的 Web 服务调用的 Rest Controller 类。
ProductServiceController.java
package com..demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com..demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@DeleteMapping(value = "/products/{id}")
public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
@PutMapping(value = "/products/{id}")
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}
@PostMapping(value = "/products")
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}
@GetMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
}
Spring Boot 应用程序类 DemoApplication.java 的代码如下所示 −
DemoApplication.java
package com..demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
Maven 构建文件 pom.xml 的代码如下所示 −
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle 构建文件 build.gradle 的代码如下所示 −
build.gradle
buildscript {
ext {
springBootVersion = '3.5.6'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 21
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
您可以使用以下 Maven 或 Gradle 命令创建可执行的 JAR 文件并运行 Spring Boot 应用程序 −
对于 Maven,可以使用以下命令 −
mvn clean install
BUILD SUCCESS 后,您可以在 target 目录下找到 JAR 文件。
对于 Gradle,可以使用以下命令 −
gradle clean build
BUILD SUCCESSFUL 后,您可以在 build/libs 目录下找到 JAR 文件。
现在,使用以下命令运行 JAR 文件 −
java jar <JARFILE>
现在,应用程序已在 Tomcat 的 8080 端口启动。
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.5.6) [2025-09-28T16:41:14Z] [org.springframework.boot.StartupInfoLogger] [main] [53] [INFO ] Starting DemoApplication using Java 21.0.6 with PID 40996 (D:\Projects\demo\target\classes started by mahes in D:\Projects\demo) [2025-09-28T16:41:14Z] [org.springframework.boot.SpringApplication] [main] [652] [INFO ] No active profile set, falling back to 1 default profile: "default" [2025-09-28T16:41:16Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [111] [INFO ] Tomcat initialized with port 8080 (http) [2025-09-28T16:41:16Z] [org.apache.juli.logging.DirectJDKLog] [main] [168] [INFO ] Initializing ProtocolHandler ["http-nio-8080"] [2025-09-28T16:41:16Z] [org.apache.juli.logging.DirectJDKLog] [main] [168] [INFO ] Starting service [Tomcat] [2025-09-28T16:41:16Z] [org.apache.juli.logging.DirectJDKLog] [main] [168] [INFO ] Starting Servlet engine: [Apache Tomcat/10.1.46] [2025-09-28T16:41:16Z] [org.apache.juli.logging.DirectJDKLog] [main] [168] [INFO ] Initializing Spring embedded WebApplicationContext [2025-09-28T16:41:16Z] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] [main] [301] [INFO ] Root WebApplicationContext: initialization completed in 1800 ms [2025-09-28T16:41:16Z] [org.apache.juli.logging.DirectJDKLog] [main] [168] [INFO ] Starting ProtocolHandler ["http-nio-8080"] [2025-09-28T16:41:16Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [243] [INFO ] Tomcat started on port 8080 (http) with context path '/' [2025-09-28T16:41:16Z] [org.springframework.boot.StartupInfoLogger] [main] [59] [INFO ] Started DemoApplication in 3.201 seconds (process running for 3.783)
现在,在 POSTMAN 应用程序中访问以下 URL,您可以看到输出结果。
通过 Rest Template 获取 Products − http://localhost:8080/template/products
创建 Products POST − http://localhost:8080/template/products
更新 Product PUT − http://localhost:8080/template/products/3
删除 Product − http://localhost:8080/template/products/3
