首页 > 其他分享 >spring5 中 RestTemplate 如何使用

spring5 中 RestTemplate 如何使用

时间:2024-10-08 14:26:27浏览次数:1  
标签:String 请求 RestTemplate springframework 如何 import org spring5

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 服务的一个简单、快速的选择。

标签:String,请求,RestTemplate,springframework,如何,import,org,spring5
From: https://www.cnblogs.com/gongchengship/p/18451542

相关文章

  • 那么使用restTemplate 的情况下,如果postForObject方法抛出了异常,那么在catch块中还能
    在使用RestTemplate的情况下,调用如postForObject()方法时,如果抛出了异常,比如HTTP4xx或HTTP5xx状态码导致的异常,默认情况下,异常中不会直接包含完整的HTTP响应体(responsebody)。然而,RestTemplate抛出的异常类确实包含了部分响应信息,比如状态码和响应头。通常,如果post......
  • 蹭暖气番外篇——如何防止被邻居蹭
    之前文章,通过热力学仿真,研究了如何更有效地蹭邻居家暖气。但是看到大家的评论,我有点儿惭愧。原来大家心地善良,皆是防守型人格,并不想占邻居家便宜,而更想知道,楼上楼下哪一户邻居停止供暖,对自己影响最大。换句话说,就是自己暖气最容易被哪一户邻居蹭。作为一个同样是防守型人格且......
  • 地图可视化的艺术:深入比较Mapbox、OpenLayers、Leaflet和Cesium,不同场景下应如何选择
    目录地图可视化的艺术:深入比较Mapbox、OpenLayers、Leaflet和Cesium一、总览二、定制地图美学的先行者——Mapbox1、主要功能特点2、开源情况3、市场与应用人群4、安装与基础使用代码三、开源GIS地图库的全能王——OpenLayers1、主要功能特点2、开源情况3、市场与应......
  • vue3如何将 app 全局变量对象变为响应式并监听到某个属性的改变
    需求:通过 getData()方法获取到数据对象,想要在屏幕方向改变的时候,给获取到的对象设置  orientation,能实时修改方案:使用reactive包裹,template直接使用全局变量下的属性,watch直接监听对应属性代码如下:main.jsconstconfig=reactive(getData())//设置屏幕方......
  • 如何优雅的摸鱼
      参考资料:探索Linux世界的趣味命令:解锁你的终端新玩法_linuxhollywood-CSDN博客一、前言在Linux的广阔世界里,隐藏着许多令人惊叹的工具和命令,一些工具和命令充满了趣味性和创意。今天让我们一起来看一下Linux命令行中有哪些既实用又有趣的命令吧!二、有趣的命令2.1 h......
  • 如何提高 Java Stream 遍历集合效率
    在Java8之前,对于大数据量的集合,传统的遍历方式主要是通过for循环或者Iterator迭代。然而,这种方式在处理大数据量集合时效率并不理想。以电商系统中的订单表为例,通常使用用户ID的Hash值来实现分表分库,以减少单个表的数据量,提高用户查询订单的速度。但当后台管理员审核订......
  • 如何让大模型更好地进行场景落地?
    自ChatGPT模型问世后,在全球范围内掀起了AI新浪潮。有很多企业和高校也随之开源了一些效果优异的大模型,例如:Qwen系列模型、MiniCPM序列模型、Yi系列模型、ChatGLM系列模型、Llama系列模型、Baichuan系列模型、Deepseek系列模型、Moss模型等。图片来自:ASurveyofLargeLa......
  • 如何保护网站免受未经授权的机器人访问
    在数字化时代,机器人流量已成为网站管理员和安全团队面临的重大挑战。机器人流量,即由自动化软件而非人类产生的网络流量,可能对网站的数据分析、安全性和整体性能产生重大影响。为了有效应对这一问题,本文将探讨一系列先进的策略,以检测和防止未经授权的机器人访问。1.使用验证码验证......
  • 网站被篡改怎么办,如何进行有效的防护
    当发现网站被篡改时,应立即采取措施以防止进一步的损害,并逐步恢复网站的正常运行。以下是一些处理和预防网站被篡改的有效步骤:立即断开服务器网络连接将受影响的服务器从网络中隔离出来,避免攻击者进一步利用该服务器进行横向移动或数据泄露。备份当前系统状态在进行任何......
  • 如何找回宝塔管理面板密码
    找回宝塔面板的密码可以通过以下几种方法实现:通过官方客户端找回:登录宝塔面板的官方网站或使用其官方客户端。在登录页面点击“忘记密码”链接。按照提示输入你的注册邮箱或手机号,并完成身份验证。重置密码并重新登录。通过数据库直接修改:如果你有服务器的SSH访问权......