我想记录整个请求和响应正文。出于日志记录的目的,jax-rs有过滤器。
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.
}
}
在响应过滤器中我无法获取请求正文。 在请求过滤器中我得到它但是:
我正在使用resteasy 3.0.6。
答案 0 :(得分:1)
1.在请求和响应使用之间建立连接:
@Override
public void filter(ContainerRequestContext paramContainerRequestContext, ContainerResponseContext paramContainerResponseContext) throws IOException {
...
}
要将流返回到主代码,请使用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));
修改强>
使用@Moritz Becker添加来自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());