I have a JAX-RS logging filter to log request and response details, something like this:
public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
...
String body = getBody(request);
...
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("request: {}", httpRequest);
}
}
}
The getBody() method reads the body content from the InputStream but I need to do some trick because I can not reset this stream. Without this little trick my rest methods always receive empty request body content:
private String getBody(final ContainerRequestContext requestContext) {
try {
byte[] body = IOUtils.toByteArray(requestContext.getEntityStream());
InputStream stream = new ByteArrayInputStream(body);
requestContext.setEntityStream(stream);
return new String(body);
} catch (IOException e) {
return null;
}
}
Is there any better way to read the body content?