public class ActivityLogInterceptor extends HandlerInterceptorAdapter {
public ActivityLogInterceptor() {
super();
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// I need the response here that has been returned in the rest api
super.postHandle(request, response, handler, modelAndView);
}
}
这是springboot HandlerInterceptorAdapter,我需要由剩余api发送的postHandle中的响应主体。我尝试了不起作用的输出流,尝试转换为对象时得到空值。
请在图像上方检出HttpServletResponse的方法,即使ModelView为null,我也无法找到内容或主体来获得确切的响应。
这应该可以解决问题:
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
final PrintWriter writer = response.getWriter();
System.out.println(writer.toString());
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
System.out.println(responseWrapper.getContentAsByteArray());
super.postHandle(request, response, handler, modelAndView);
}
ContentCachingResponseWrapper
用于从ServletResponse获取内容。我可以从REST API中看到响应结果,但是当我尝试打印时,内容长度为0。
上图显示了来自其余api的结果,但是当我尝试获取拦截器中的内容为空且内容长度为0时。