首页 > 解决方案 > 如何使用 Spring 5 WebClient 进行头部调用

问题描述

我无法使用 WebClient 对休息服务进行 HEAD 调用。我只想读取计数标头,因为需要在进一步的其余调用中使用相同的标头,如何实现相同的实现如何将 Mono> 转换为整数计数值。GET 调用成功但是 HEAD 调用总是失败,我使用以下代码:

private void getResultCount(WebClient webClient)
{

     Mono<ClientResponse> response = webClient.head()
        .uri("/rest/v2/electronics/products/search/?query=::category:575:")
        .exchange()
        .doOnSuccess(clientResponse -> System.out.println("clientResponse.headers() = " + clientResponse.headers()));


     System.out.println("response "+response);
}

标签: springspring-bootreactive-programmingspring-webflux

解决方案


我认为您要问的是如何从 Head 调用中提取信息,当它的响应在 HEADERS 中而不是在正文中时,我需要类似的东西,过了一会儿我发现了这篇baeldung 文章

我的解决方案是:

var aHeader = aClient.head()
        .retrieve()
        .toEntity(String.class)
        .map(aResponse -> aResponse.getHeaders())
        .block();
System.out.println(aHeader);

推荐阅读