Spring Boot 3.2 RestClient 同步 HTTP 客户端

Spring Boot HTTP About 1,295 words

HTTP 客户端

Spring 5.0提供了WebClient基于Spring WebFlux的异步HTTP客户端。

Spring 6.1提供了RestClient基于RestTemplate的同步HTTP客户端。

RestClient

实例化

RestClient restClient = RestClient.create();

body 返回内容

String result = restClient.get()
        .uri("https://www.baidu.com")
        .retrieve()
        .body(String.class);

toEntity 转为 ResponseEntity

ResponseEntity包含了状态码等额外信息。

ResponseEntity<String> response = restClient.post()
        .uri("https://www.baidu.com")
        .retrieve()
        .toEntity(String.class);
System.out.println(response);

contentType/body 请求类型及请求体

class RequestBody {
    public String id;
    public String name;
}

RequestBody requestBody = new RequestBody();
String body = restClient.post()
        .uri("https://www.baidu.com")
        .contentType(MediaType.APPLICATION_JSON)
        .body(requestBody)
        .retrieve()
        .body(String.class);
System.out.println(body);

onStatus 错误处理

String res = restClient.get()
        .uri("https://www.baidu.com")
        .retrieve()
        .onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
            System.out.println(response.getStatusCode() + " " + response.getHeaders());
        })
        .body(String.class);
System.out.println(res);

更多内容

https://spring.io/blog/2023/07/13/new-in-spring-6-1-restclient

Views: 1,014 · Posted: 2023-07-19

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh