拦截 WebClient 请求响应数据,遇到 Only one connection receive subscriber allowed。
@Test
public void testWebClient2() {
WebClient client = WebClient.builder()
.filter(logResponse()).build();
Mono<String> mono = client.get().uri("https://www.baidu.com").retrieve().bodyToMono(String.class);
System.out.println(mono.block());
}
private ExchangeFilterFunction logResponse() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
log.info("Response Status : " + clientResponse.statusCode());
Mono<String> body = clientResponse.bodyToMono(String.class);
body.subscribe(str -> System.out.println(str));
return Mono.just(clientResponse);
});
}
运行结果:
java.lang.IllegalStateException: Only one connection receive subscriber allowed.
at reactor.netty.channel.FluxReceive.startReceiver(FluxReceive.java:304)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ Body from GET https://www.baidu.com [DefaultClientResponse]
Stack trace:
at reactor.netty.channel.FluxReceive.startReceiver(FluxReceive.java:304)
filter里面消费了response body, 业务代码就不能消费了,目的是收集 WebClient 的请求和响应数据,有什么方式解决吗?求解,谢谢。
你可以尝试下这个。不过这违背了流的初衷,属于非主流操作。