How to intercept http response traffic in Spring WebClient / DataBuffer?

情到浓时终转凉″ 提交于 2019-12-13 03:15:14

问题


How can I intercept WebClient XML responses before they are converted from bytes to DTO?

I tried adding an exchangeStrategy, but how could I convert DataBuffer to String, and afterwards still invoke the super.decode() method?

ExchangeStrategies.builder().codecs((configurer) -> {
    configurer.defaultCodecs().jackson2JsonDecoder(new Jaxb2XmlDecoder() {
        @Override
        public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
            //TODO how to log the response as string content? 
            return super.decode(inputStream, elementType, mimeType, hints);
        }
    }));

I succeeded as follows, but I don't know if that is the correct solution? Especially returning an empty collection inside the flatMapInterable() feels wrong, but I did not find another way to make it work.

@Override
public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
    return DataBufferUtils.join(inputStream)
            .flatMapIterable(buffer -> {
                try {
                    LOGGER.info(StandardCharsets.UTF_8.decode(buffer.asByteBuffer()).toString());
                    return Collections.emptyList();
                } finally {
                    DataBufferUtils.release(buffer);
                }
            })
            .map(arg -> super.decode(inputStream, elementType, mimeType, hints));
}

Problem: map() is not executed anymore due to the fact that I already read the DataBuffer. How could I read it multiple times?


回答1:


So far I came up with the following solution. It works, but I'm still open for improvements as I don't even know if I'm doing this correctly here.

@Override
public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
    return DataBufferUtils.join(inputStream)
            .doOnNext(buf -> LOGGER.info(StandardCharsets.UTF_8.decode(buf.asByteBuffer()).toString()))
            .flatMapMany(buf -> super.decode(Mono.fromSupplier(() -> buf), elementType, mimeType, hints));
}


来源:https://stackoverflow.com/questions/57037543/how-to-intercept-http-response-traffic-in-spring-webclient-databuffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!