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));
    }
}
相关推荐
袁煦丞 cpolar内网穿透实验室11 小时前
无需公网 IP 也能全球访问本地服务?cpolar+Spring Boot+Vue应用实践!
vue.js·spring boot·tcp/ip·远程工作·内网穿透·cpolar
踏浪无痕11 小时前
告别 Grafana 手搓 Dashboard:基于指标分组的 Prometheus 可视化新方案
后端·架构·产品
天天摸鱼的java工程师11 小时前
分布式 ID 生成终极方案:雪花算法优化与高可用实现
java·后端
掘金者阿豪11 小时前
Jenkins 任务中的 `java.lang.InterruptedException` 异常解析与解决
后端
superman超哥11 小时前
Rust 零拷贝技术应用:极致性能的内存操作艺术
开发语言·后端·rust·rust零拷贝技术·内存操作
间彧11 小时前
深度解析AIOps:从架构设计到工具实践的智能运维体系
后端
superman超哥11 小时前
Rust SIMD 指令优化:数据并行的极致性能
开发语言·后端·rust·数据并行·指令优化
不染尘.11 小时前
DHCP和HTTP2_3
服务器·网络·网络协议·计算机网络·http·udp·tcp
幽络源小助理11 小时前
SpringBoot+Vue雅苑小区管理系统源码 | Java物业项目免费下载 – 幽络源
java·vue.js·spring boot
嘻哈baby11 小时前
慢SQL排查与优化实战:从定位到根治
后端