I want to log entire request and response body. For logging purposes jax-rs have filters.
public class ResponseLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
System.out.println(IOUtils.toString(requestContext.getEntityStream(), "UTF-8")); // It's always empty string
System.out.println(responseContext.getEntity().toString()); // Here is actual response. It's OK
}
public void filter(ContainerRequestContext requestContext) throws IOException {
System.out.println(IOUtils.toString(requestContext.getEntityStream(), "UTF-8")); // Here is actual response. But this request is empty in main code.
}
}
In response filter I cant get request body. In request filter I cat get it but:
I'm using resteasy 3.0.6.
1.To have connection between request and response use:
@Override
public void filter(ContainerRequestContext paramContainerRequestContext, ContainerResponseContext paramContainerResponseContext) throws IOException {
...
}
To return the stream to Main code write it back with setEntityStream
:
ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = requestContext.getEntityStream(); final StringBuilder b = new StringBuilder(); try { ReaderWriter.writeTo(in, out); byte[] requestEntity = out.toByteArray(); ... requestContext.setEntityStream(new ByteArrayInputStream(requestEntity));
EDIT
Adding using @Moritz Becker comment example of link between request body and response body from ClientLoggingFilter :
@Override public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) throws IOException { ... final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY); final long id = requestId != null ? (Long) requestId : _id.incrementAndGet(); final StringBuilder b = new StringBuilder(); printResponseLine(b, "Client response received", id, responseContext.getStatus()); printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.