我有下面的代码,我正在尝试使用 ContainerResponseContext 获取和打印响应正文。但是,它返回 null。我可以使用 responseContext.getStatus() 等 getter 从“ContainerResponseContext”获取其他详细信息。请注意,我不想在任何地方使用“WriterInterceptor”和 Lombok 的“aroundWriteTo”。任何帮助表示赞赏。谢谢!!
public void getResponseBody(ContainerResponseContext context) throws IOException {
OutputStream originalStream = context.getEntityStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
context.setEntityStream(baos);
LOG.info("Payload output Stream(Response with Payload, ContainerResponseContext) : " + baos.toString());
baos.writeTo(originalStream);
baos.close();
context.setEntityStream(originalStream);
}
调用上面的“getResponseBody”方法如下:
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
if(responseContext.hasEntity()) { getResponseBody(responseContext); }
responseContext.getHeaders();
LOG.info("--------Start Response without Payload content--------");
LOG.info("Response Details: Response status:" + responseContext.getStatus()+
" ,Response Info:"+responseContext.getStatusInfo());
MultivaluedMap<String, Object> map = responseContext.getHeaders();
for (Entry<String, List<Object>> entry : map.entrySet()) {
String k = entry.getKey(); List<Object> v = entry.getValue();
LOG.info("Key Response: " + k + ", Response Value: " + v); }
if(responseContext.hasEntity()) {
getResponseBody(responseContext);
}
LOG.info("--------End Response without Payload content--------");
}