如何在 Spring WebClient 中拦截 http 流量?

How to intercept http traffic in Spring WebClient?

如何在 WebFilter 请求从 DTO 转换为 JSON 字符串后拦截它们?

当然我可以添加一个 ExchangeFilterFunction,但是 clientRequest.body() 只显示我的输入对象,而不是转换后的 json 字符串:

WebClient.builder().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).filter(logRequest()).build();

private ExchangeFilterFunction logRequest() {
    return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
        LOGGER.info(clientRequest.body()); //body is MyRequest.class
        return Mono.just(clientRequest);
    });
}

MyRequestDto dto;
client.post().uri(url).syncBody(dto).retrieve().bodyToMono(MyResponseDto.class).block();

所以我正在寻找一种方法来拦截从 dto 转换为 json 字符串后的传出请求。

反过来,拦截响应 before 它们从 json.

转换为 dto

JacksonEncoder 将数据写入 String 而不是 DataBuffer 中的字节。拦截请求的一种方法是覆盖 JSON 编码器,并直接访问 DataBuffer 或将其解释为 String.

Consumer<ClientCodecConfigurer> consumer = configurer ->
        configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder() {
            @Override
            public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
                return super.encode(inputStream, bufferFactory, elementType, mimeType, hints)
                        .doOnNext(dataBuffer -> System.out.println(StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer()).toString()));
            }
        });

WebClient webClient = WebClient.builder()
        .exchangeStrategies(ExchangeStrategies.builder().codecs(consumer).build())
        .build();

如果目的只是记录外发邮件正文,请参阅此问题: