我正在尝试通过以下方式在Web-flux中记录请求正文:webflux-demo 但是,即使我传递请求正文,也总是以空字符串结尾。 requestBody.map无法执行。它跳过该块。我想念什么?
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
if(logging.enabled()){
ServerHttpRequest request = exchange.getRequest();
System.out.println("Request body : " + getRequestBody(request));
return chain.filter(exchange);
} else {
return chain.filter(exchange);
}
}
private String getRequestBody(ServerHttpRequest request) {
final ServerHttpRequest decorated = new ServerHttpRequestDecorator(request);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Flux<DataBuffer> requestBody = decorated.getBody();
requestBody.map(dataBuffer -> {
try {
Channels.newChannel(byteArrayOutputStream)
.write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
} catch (IOException e) {
logger.error("Unable to log input request due to an error", e);
}
return dataBuffer;
});
return byteArrayOutputStream.toString();
}