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));
    }
}
相关推荐
码农阿豪4 分钟前
群晖部署Moodist配内网穿透穿透,把白噪音服务搬到公网上
数据库·spring boot·后端
0xDevNull34 分钟前
Spring中统一异常处理详细教程
java·开发语言·后端
abcefg_h37 分钟前
GORM——基础介绍与CRUD
开发语言·后端·golang
MuzySuntree38 分钟前
Ubuntu 下 Maven 构建 Spring Boot 项目报错 release version 17 not supported 解决方案
spring boot·ubuntu·maven
白驹笙鸣40 分钟前
HTTP(1)
网络·网络协议·http
Undoom1 小时前
告别“复读机”:深度拆解星云 SDK 如何破解数字人实时交互的“不可能三角”
后端
weixin_408099671 小时前
Lua请求文字识别ocr api
图像处理·人工智能·后端·ocr·lua·api·文字识别
想不明白的过度思考者1 小时前
一个叫Swagger的工具,让写接口文档变成享受
java·spring boot·接口·swagger
zshs0001 小时前
重读《凤凰架构》,从分布式演进史看技术选型的本质
分布式·后端·架构
Devin~Y11 小时前
大厂Java面试实录:Spring Boot/Cloud、Kafka、Redis、K8s 与 Spring AI(RAG/Agent)三轮连环问
java·spring boot·redis·mysql·spring cloud·kafka·kubernetes