【问题标题】:Common processing/validation of response body in WebClientWebClient中响应体的通用处理/验证
【发布时间】:2019-08-29 10:02:25
【问题描述】:

我有一个类似 REST 的服务,我使用 WebFlux WebClient 发布请求。该服务以常见的 JSON 格式返回响应,例如:

{
    "status": "OK",
    "data": []
}

现在对于每个端点的每个 WebClient 调用,我想执行通用验证以检查 status == "OK"。我是否需要为每个端点单独调用验证,例如

myClient.post().uri("/myEndpoint1")
    //..
    .retrieve()
    .bodyToMono(MyResponse.class)
    .map(this::validateResponse)
    //..

或者有没有办法在创建 WebClient 时添加一些常见的处理。我尝试使用过滤器

this.myClient = WebClient.builder()
    .clientConnector(new ReactorClientHttpConnector(HttpClient.create().wiretap()))
.filter(ExchangeFilterFunction.ofResponseProcessor(this::validateMyResponseAsFilter))
    .baseUrl(mybaseUrl)
    .build();

validateMyResponseAsFilter 在哪里

private Mono<ClientResponse> validateMyResponseAsFilter(ClientResponse resp) {
    return resp.bodyToMono(MyResponse.class)
        .flatMap(myResponse -> "OK".equals(myResponse.getStatus()) ? Mono.just(resp) : Mono.error(new RuntimeException()));
  }

但这会导致

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/octet-stream' not supported for bodyType=my.package.MyResponse

【问题讨论】:

    标签: spring-webflux


    【解决方案1】:

    原来我连接的服务没有返回 Content-Type 标头。修复服务后,代码正常运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 2023-04-10
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多