如何在Spring Boot拦截器中从HttpServletReponse获取内容

问题描述 投票:0回答:2
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中的响应主体。我尝试了不起作用的输出流,尝试转换为对象时得到空值。

enter image description here

请在图像上方检出HttpServletResponse的方法,即使ModelView为null,我也无法找到内容或主体来获得确切的响应。

java spring-boot servlets interceptor
2个回答
0
投票

这应该可以解决问题:

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    final PrintWriter writer = response.getWriter();
    System.out.println(writer.toString());
}

0
投票
@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。

enter image description here

上图显示了来自其余api的结果,但是当我尝试获取拦截器中的内容为空且内容长度为0时。

© www.soinside.com 2019 - 2024. All rights reserved.