学无先后,达者为师

网站首页 编程语言 正文

SpringBoot中RestTemplate 发送http请求

作者:Bunny0212 更新时间: 2024-03-14 编程语言

SpringBoot中RestTemplate 发送http请求

引入fastjson

<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.47</version>
</dependency>

创建配置文件

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

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

发送请求

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

创建UserVo类

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

@Data
public class UserVo {
    private Integer userId;
    private Integer id;
    private String title;
    private Boolean completed;
}

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

@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));
    }
}

在这里插入图片描述

原文链接:https://blog.csdn.net/weixin_46533577/article/details/136610993

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新