如何在将WebClient
XML响应从字节转换为DTO之前进行拦截?
我尝试添加exchangeStrategy
,但是如何将DataBuffer
转换为String,然后仍然调用super.decode()
方法呢?
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);
}
}));
我成功获得了以下成功,但是我不知道这是否是正确的解决方案?尤其是在flatMapInterable()
内部返回一个空集合感觉很不对劲,但是我没有找到其他使之起作用的方法。
@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));
}
问题:由于我已经读过map()
,因此不再执行DataBuffer
。我怎样才能多次阅读?
答案 0 :(得分:0)
到目前为止,我想出了以下解决方案。它可以工作,但是我仍然愿意进行改进,因为我什至不知道我在这里是否做得正确。
@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));
}