spring5 中 RestTemplate 如何使用

Spring 5 中,RestTemplate 是一个用于同步地执行 HTTP 请求并消费 RESTful Web 服务的客户端工具。尽管 RestTemplate 已被建议逐步被替代为 WebClient(Spring WebFlux 的一部分)以支持响应式编程模型,但它仍然是处理同步请求的常用工具之一,并且在许多现有项目中广泛使用。

基本使用步骤:

  1. 引入 Spring Web 依赖
    你需要在 pom.xml 中引入 Spring Web 依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  2. 配置 RestTemplate Bean
    虽然可以直接创建 RestTemplate 实例,但通常我们通过 @Bean 的方式在 Spring 配置类中配置 RestTemplate,以便进行更好地管理。

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

    通过这个方式,你可以在任何需要的地方通过 依赖注入 来使用 RestTemplate

  3. 发送 HTTP 请求
    RestTemplate 提供了一些常用的 HTTP 操作方法,如 GET, POST, PUT, DELETE,你可以根据需求使用不同的操作。以下是几个常见的用法。

1. GET 请求

通过 getForObject()getForEntity() 来执行 GET 请求。getForObject() 直接返回响应体的对象,而 getForEntity() 返回带有状态码、响应头等信息的 ResponseEntity

示例代码:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MyService {

    @Autowired
    private RestTemplate restTemplate;

    public String getExample() {
        String url = "https://api.example.com/data";
        
        // getForObject 直接获取响应体
        String result = restTemplate.getForObject(url, String.class);

        // 或者使用 getForEntity 来获取整个响应对象
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        return response.getBody();  // 获取响应体
    }
}

2. POST 请求

postForObject()postForEntity() 可以用于发送 POST 请求。你可以将数据传递给服务器并接收响应。

示例代码:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MyService {

    @Autowired
    private RestTemplate restTemplate;

    public String postExample() {
        String url = "https://api.example.com/data";
        
        // 准备请求数据
        String requestBody = "{\"key\":\"value\"}";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 包装请求体
        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求并获取响应
        String response = restTemplate.postForObject(url, request, String.class);

        return response;
    }
}

3. PUT 请求

put() 方法用于更新资源,类似于 POST,但主要用于更新现有的资源。

示例代码:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MyService {

    @Autowired
    private RestTemplate restTemplate;

    public void putExample() {
        String url = "https://api.example.com/data/123";  // 假设 123 是要更新的资源的 ID
        
        // 准备请求体
        String updatedData = "{\"name\":\"updatedName\"}";

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 包装请求体
        HttpEntity<String> request = new HttpEntity<>(updatedData, headers);

        // 发送 PUT 请求
        restTemplate.put(url, request);
    }
}

4. DELETE 请求

delete() 方法用于删除资源。

示例代码:

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MyService {

    @Autowired
    private RestTemplate restTemplate;

    public void deleteExample() {
        String url = "https://api.example.com/data/123";  // 假设 123 是要删除的资源的 ID
        
        // 发送 DELETE 请求
        restTemplate.delete(url);
    }
}

5. 处理异常

RestTemplate 可以抛出多种异常,比如 HttpClientErrorExceptionHttpServerErrorException。可以通过捕获这些异常来处理错误响应。

示例代码:

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Service
public class MyService {

    @Autowired
    private RestTemplate restTemplate;

    public String handleErrors() {
        String url = "https://api.example.com/data";

        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            // 处理 4xx 错误
            return "Client Error: " + e.getStatusCode();
        } catch (Exception e) {
            // 处理其他错误
            return "Error occurred: " + e.getMessage();
        }
    }
}

总结:

  • GET: 使用 getForObject()getForEntity() 发送 GET 请求。
  • POST: 使用 postForObject()postForEntity() 发送 POST 请求,传递请求体并接收响应。
  • PUT: 使用 put() 方法更新现有资源。
  • DELETE: 使用 delete() 方法删除资源。
  • 你可以通过 HttpHeaders 来设置请求头信息,比如 Content-TypeAuthorization 等。
  • RestTemplate 适用于同步请求,尽管 Spring 推荐使用 WebClient 进行响应式编程,但 RestTemplate 仍然是构建 RESTful 服务的一个简单、快速的选择。
posted @   gongchengship  阅读(104)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示