How to intercept http response traffic in Spring W

2019-08-17 20:17发布

问题:

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));
}