日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新