如何在过滤器方法中将响应消息正文打印为字符串,并尝试了几种响应方法(getEntityOutputStream() / getEntity() / GetContainerResponseWriter() )
public class Test implements ContainerRequestFilter , ContainerResponseFilter) {
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
response.
}
}
答案 0 :(得分:0)
我使用Jersey日志记录打印出请求/响应正文
在我的ResourceConfig
中registerInstances(new LoggingFilter(myLogger, true));
LoggingFilter的
public class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter,
ClientResponseFilter, WriterInterceptor {
...
您可以查看他们是如何做到的:https://github.com/jersey/jersey/blob/master/core-common/src/main/java/org/glassfish/jersey/filter/LoggingFilter.java
答案 1 :(得分:0)
我遇到了同样的问题,这就是我最终要做的事情。基本上我返回我的实体的JSON表示,如果我可以投射它,否则我创建一个自定义响应消息。
我相信会有更好的方法来做到这一点。
private String createLoggingResponse(ContainerResponseContext resp) {
Object entity = resp.getEntity();
if (BaseModel.class.isInstance(entity)) {
BaseModel model = (BaseModel) entity;
ByteArrayOutputStream out = new ByteArrayOutputStream();
model.toJson(out);
return new String(out.toByteArray());
} else {
MediaType mediaType = resp.getMediaType();
return "[" + entity.toString() + "," + resp.getStatusInfo().getStatusCode() + "," + resp.getStatusInfo().getReasonPhrase() + "," + mediaType.toString() + "]";
}
}