RestClient 使用

102 阅读1分钟

RestClient 是什么

RestClient 是 spring 6 提供的发送HTTP请求的同步客户端工具。

如果是新项目推荐使用RestClient替代RestTemplate

创建实例

有两种方式创建

@Configuration
public class RestClientConfig {
    
    @Bean
    public RestClient restClient() {
        return RestClient.create();
    }

}

或者

@Configuration
public class RestClientConfig {

    @Bean
    public RestClient restClient(RestClient.Builder builder) {
        return builder.build();
    }

}

实际生产更推荐使用这种方式。

发送请求

GET请求

String body = restClient.get()
        .uri("http://localhost:9090/api/hello/{id}", 1)
        .retrieve()
        .body(String.class);

如果是集合类型:

List<String> body = restClient.get()
        .uri("http://localhost:9090/api/hello/{id}", 1)
        .retrieve()
        .body(new ParameterizedTypeReference<List<String>>() {});

也可以对URL进行编码

URI uri = UriComponentsBuilder.fromUri(URI.create("http://localhost:9090"))
        .path("/api/hello/{id}")
        .buildAndExpand(1)
        .toUri();

String body = restClient.get()
        .uri(uri)
        .retrieve()
        .body(String.class);

如果还关心响应头等数据,可以接收 ResponseEntity:

ResponseEntity<String> body = restClient.get()
        .uri("http://localhost:9090/api/hello/{id}", 1)
        .retrieve()
        .toEntity(String.class);

POST请求

UserDto user = new UserDto("Alice", 25);

String response = restClient.post()
        .uri("https://example.com/api/users")
        .contentType(MediaType.APPLICATION_JSON)
        .body(user)  // 直接传入对象
        .retrieve()
        .body(String.class);  // 直接解析为 DTO 对象

PUT请求

UserDto user = new UserDto("Alice", 25);

String response = restClient.put()
        .uri("https://example.com/api/users")
        .contentType(MediaType.APPLICATION_JSON)
        .body(user)  // 直接传入对象
        .retrieve()
        .body(String.class);  // 直接解析为 DTO 对象

DELETE请求

restClient.delete()
        .uri("https://jsonplaceholder.typicode.com/posts/1")
        .retrieve()
        .toBodilessEntity();  // 无响应体,仅确认操作成功

配置

@Configuration
public class RestClientConfig {

    @Bean
    public RestClient restClient(RestClient.Builder builder, ClientHttpRequestFactory clientHttpRequestFactory) {
        return builder
                .requestFactory(clientHttpRequestFactory)
                .build();
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

        requestFactory.setConnectTimeout(5000); // 设置链接超时 5s
        requestFactory.setReadTimeout(10000);   // 设置读取超时 10s

        return requestFactory;
    }

}

异常

异常类和RestTemplate异常一样。

通用异常是 RestClientException

4xx异常:HttpClientErrorException

5xx异常:HttpServerErrorException

网络错误:ResourceAccessException