Hi, I use Spring Webflux with Spring Boot 3.1.0. I use this code snippet to log my request body on each request, but since Spring 6.0 I have no alternative to this deprecated method (toByteBuffer() ). Could you help me please ?
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
Channels.newChannel(byteArrayOutputStream).write(dataBuffer.toByteBuffer().asReadOnlyBuffer());
String requestBody = IOUtils.toString(byteArrayOutputStream.toByteArray(), "UTF-8");
log.trace("Request body = {} ", requestBody);
} catch (IOException e) {
e.printStackTrace();
}
Comment From: mdeinum
The javadoc explains which other method to use.
Use the toByteBuffer(ByteBuffer)
method. So create the ByteBuffer
yourself. Another option is to use the asInputStream
, then use the StreamUtils
to copy from the input to the outputstream and then create the String.
Comment From: guillaume-1
@mdeinum Thank you, I managed to do it work with your advices. My code for the others :
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, 0, bytes.length);
dataBuffer.toByteBuffer(byteBuffer);
Channels.newChannel(byteArrayOutputStream).write(byteBuffer);
String requestBody = IOUtils.toString(byteArrayOutputStream.toByteArray(), "UTF-8");
exchange.getAttributes().put("ContentCachingRequest", requestBody);
} catch (IOException e) {
e.printStackTrace();
}
Have a good day !
Comment From: mdeinum
Is there a reason not to use DataBuffer.toString(StandardCharsets.UTF-8);
instead of what you have now?
Comment From: guillaume-1
My bad... absolutely no, I haven't seen this method, it does the job. Thank you !
Comment From: missingfaktor
Is there a reason not to use DataBuffer.toString(StandardCharsets.UTF-8); instead of what you have now?
Thanks, @mdeinum. I was going crazy finding alternatives to the deprecated DataBuffer#asByteBuffer
. Your comment helped.