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));
    }
}
相关推荐
Victor3561 小时前
MongoDB(31)索引对查询性能有何影响?
后端
Victor3561 小时前
MongoDB(30)如何删除索引?
后端
lizhongxuan2 小时前
多 Agent 协同机制对比
后端
IT_陈寒2 小时前
SpringBoot项目启动慢?5个技巧让你的应用秒级响应!
前端·人工智能·后端
树上有只程序猿2 小时前
2026低代码选型指南,主流低代码开发平台排名出炉
前端·后端
高端章鱼哥3 小时前
为什么说用OpenClaw对打工人来说“不划算”
前端·后端
大脸怪3 小时前
告别 F12!前端开发者必备:一键管理 localStorage / Cookie / SessionStorage 神器
前端·后端·浏览器
用户8356290780513 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
架构师沉默3 小时前
别又牛逼了!AI 写 Java 代码真的行吗?
java·后端·架构
zone77394 小时前
006:RAG 入门-面试官问你,RAG 为什么要切块?
后端·算法·面试