SpringBoot中RestTemplate 发送http请求

SpringBoot中RestTemplate 发送http请求

引入fastjson

xml 复制代码
<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.47</version>
</dependency>

创建配置文件

新建config包,并写入以下内容,在spring启动时加载bean到ioc容器中

java 复制代码
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

发送请求

请求为:https://jsonplaceholder.typicode.com/todos/1

创建UserVo类

方便之后使用方法返回作为转换类型

java 复制代码
@Data
public class UserVo {
    private Integer userId;
    private Integer id;
    private String title;
    private Boolean completed;
}

ResponseEntity加入UserVo泛型,在response返回中状态码有2xx和3xx等几种类型的返回状态码使用非常方便。

java 复制代码
@Test
void contextLoads() {
    // 发送请求
    ResponseEntity<UserVo> response = restTemplate.exchange("https://jsonplaceholder.typicode.com/todos/1",
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<>() {
            });

    // 判断状态码
    if (response.getStatusCode().is2xxSuccessful() || response.getStatusCode().is3xxRedirection()) {
        UserVo body = response.getBody();
        // 输出转成JSON
        System.out.println(JSON.toJSON(body));
    }
}
相关推荐
Scene2164 分钟前
Agent Harness、Loop 与 Graph:构建生产级 AI Agent 的三大架构支柱
后端
SomeB1oody29 分钟前
【RustyML入门】2.0. 经典机器学习
开发语言·后端·机器学习·rust·教程
就改了34 分钟前
SpringBoot 自定义线程池 + 实时监控指标
java·spring boot·后端
暗黑小白41 分钟前
脱敏引擎工程化
后端·ai agent
用户81818706274644 分钟前
第23章 JPA / Hibernate 异常
后端
用户8181870627461 小时前
第22章 MyBatis / MyBatis-Plus 常见异常与 SQL 调试
后端
雪隐1 小时前
个人电脑玩AI-15让5060 Ti给你打工——MiniMax H3 本地部署实录:一个自带录音棚的视频模型,和它的 NVFP4 瘦身奇遇
前端·人工智能·后端
玖石书2 小时前
ASP.NET Core 迁移至 Spring系列:类库框架篇
java·后端·asp.net
PieroPC3 小时前
Windows 驱动备份与恢复工具 CMD bat
后端
Csvn3 小时前
📊 SQL 入门 Day 12: 窗口函数基础
后端·sql