猿问

使用新参数重复 WebClient 获取

我正在开发一个 Spring WebFlux 应用程序,并且我有一个 Web 适配器,用于调用我使用的外部 api 方法。其中一个 api 使用带有 rel="next" 的链接标头具有分页结果。我需要调用这个 api,直到下一个链接不存在,但我不确定如何实现这一点。以下是我目前正在使用的基本调用:


public Flux<ItemDto> getAllItems(){

   return webClient.get() //The headers and base url for the api are defined in the constructor

        .uri("/api/items?limit=200") //limit is the number of items returned with 200 being the maximum

        .retrieve()

        .bodyToFlux(Map.class)

        .map(ItemConverter::mapValueToItemDto);//This is just a conversion method that handles mapping

}

我需要的是能够重复此调用,但添加一个请求参数,该参数基于具有“下一个”rel 值的链接标头的一部分。


我已经看到提到使用扩展或重复,但我不确定如何准确使用它们。我知道使用 exchange 是获取 clientResponse 所必需的,因此我可以获得标头。


这个问题可能相当模糊,所以如果需要,我可以提供任何澄清。


慕哥6287543
浏览 133回答 1
1回答

ABOUTYOU

经过大量试验和错误并找到特定部分的解决方案后,我找到了适合我的解决方案。public Flux<ItemDto> getAllItems() {&nbsp; &nbsp; webClient.get()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .uri("/api/items?limit=1")//Used one to test&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .exchange()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .expand(clientResponse -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<String> links = clientResponse.headers().asHttpHeaders().getValuesAsList("LINK");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(links.stream().anyMatch(link->link.contains("rel=\"next\""))){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (String link : links){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (link.contains("rel=\"next\"")){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return webClient.get()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .uri("/api/items?limit=1&" + link.substring(link.indexOf("after="), link.indexOf("&")))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .exchange();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Flux.empty();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(clientResponse ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clientResponse.bodyToFlux(Map.class)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(ItemConverter::mapValueToItemDto));}不需要任何递归。只是更合适地使用扩展。现在,其中的一部分(见下文)实际上可以分解成自己的方法,但由于它只有几行,我选择不这样做。webClient.get()&nbsp; &nbsp;.uri("/api/items?limit=1" + after)//This after bit would be like what was passed as an argument before&nbsp; &nbsp;.exchange();
随时随地看视频慕课网APP

相关分类

Java
我要回答