使用JAX-RS resteasy和ContainerRequestFilter / ContainerResponseFilter

时间:2017-09-07 05:10:06

标签: java logging jax-rs resteasy

我想记录整个请求和响应正文。出于日志记录的目的,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。

1 个答案:

答案 0 :(得分:1)

1.在请求和响应使用之间建立连接:

@Override
    public void filter(ContainerRequestContext paramContainerRequestContext, ContainerResponseContext paramContainerResponseContext) throws IOException {
        ...     
    }
  1. 要将流返回到主代码,请使用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));
    
  2. 修改

    使用@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());