【问题标题】:How to convert Spring WebClient Response to ResponseEntity?如何将 Spring WebClient 响应转换为 ResponseEntity?
【发布时间】:2022-01-19 19:54:18
【问题描述】:

我可以使用 toEntity() 方法返回 ResponseEntity,如下所示:

@GetMapping("/uri")
public Mono<ResponseEntity<Data[]>> methodName() {
    return webClient
            .get()
            .uri("http://localhost:8088/externalService")
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .toEntity(Data[].class);
}

但我想在返回之前处理响应标头。 上面的代码将 WebClient 响应转换为 ResponseEntity 并立即返回,但我想将其存储在 ResponseEntity 变量中,对其进行处理,然后将 ResponseEntity 返回。

我提到了这个 -> Spring WebClient Documentation

当我尝试将其存储在变量中时,我收到此错误 ->“block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-nio-3 不支持”

【问题讨论】:

    标签: java spring spring-boot webclient spring-webclient


    【解决方案1】:

    您可以简单地使用 Reactor 的 map 运算符来修改标头:

    return webClient
            .get()
            .uri("http://localhost:8088/externalService")
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .toEntity(Data[].class)
            .map(responseEntity ->  responseEntity.getHeaders().add("header", "header-value");
    

    或者,您可以使用.handle 运算符来提供响应处理:

    .handle((responseEntity, sink) -> {
            if(!isValid(responseEntity)){
                sink.error(new InvalidResponseException());
            } else if (isOk(responseEntity))
                sink.next(responseEntity);
            }
            else {
                //just ignore element
            }
        })
    

    【讨论】:

    • 我想做类似下面的事情。 ResponseEntity&lt;Data&gt; responseEntity = webClient .get() .uri("http://localhost:8088/externalService") .accept(MediaType.APPLICATION_JSON) .retrieve() .toEntity(Data[].class); 在 ResponseEntity 中检查一些东西并返回它。如果我将它分配给一个变量,我会收到此错误 ->“block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-nio-3 不支持”
    • @HarishankarBhatR 你是什么意思“检查什么?”
    • 验证响应头等。为此,我需要从 WebClient 响应中获取响应实体。
    • @HarishankarBhatR 编辑完成
    • 在这个documentation 中,WebClient 响应被分配给这个变量: Mono> entityMono 。但是从 Mono> entityMono,我需要获取 ResponseEntity 对象。如果我执行 entityMono.block() 会收到错误“block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-nio-3 不支持该错误”
    猜你喜欢
    • 2021-08-30
    • 1970-01-01
    • 2019-05-17
    • 2020-07-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多