使用resteasy记录json帖子

sim*_*onC 6 post logging json resteasy

我正在寻找一种在RESTEASY框架中记录JSON帖子的方法.

我想将POST主体记录到日志文件中以查看客户端发送给我的内容.

有没有我可以使用的拦截器或类似的东西,我找到了一个PreProcessInterceptor的例子,但看起来它已被弃用.

我正在使用resteasy 3.0.8

lef*_*loh 7

您可以使用ContainerRequestFilter:

@Provider
public class LogFilter implements ContainerRequestFilter {

    private Logger LOG = LoggerFactory.getLogger(LogFilter.class);

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        if (!"POST".equals(requestContext.getMethod()) 
                || !MediaType.APPLICATION_JSON_TYPE.equals(requestContext.getMediaType())
                || requestContext.getEntityStream() == null) {
            return;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(requestContext.getEntityStream(), baos);
        byte[] bytes = baos.toByteArray();
        LOG.info("Posted: " + new String(bytes, "UTF-8"));
        requestContext.setEntityStream(new ByteArrayInputStream(bytes));

    }

}
Run Code Online (Sandbox Code Playgroud)

您也可以只在需要的地方按@NameBinding注册此过滤器,而不是检查方法和内容类型.

注意:这个简单的示例复制了请求的InputStream,因此它将被读取两次(可能是性能问题).