I have custom Filter and I want to log body from request.
But when I use ContentCachingRequestWrapper and try to call getContentAsByteArray() I always get an empty array.
@Component
public class CustomFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(CustomFilter.class);
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest requestToCache = new ContentCachingRequestWrapper(request);
chain.doFilter(req, res);
log.info(getRequestData(requestToCache));
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
public static String getRequestData(final HttpServletRequest request) throws UnsupportedEncodingException {
String payload = null;
ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
}
}
return payload;
}
}
I also tried create Interceptor, but had the same problem.
What am I doing wrong?
Thanks for help.
ContentCachingRequestWrapperbefore your call togetRequestData, where it's creating anotherContentCachingRequestWrapper? I suspect because it reads the body when you create the firstContentCachingRequestWrapperthat it can't re-read from the buffer when creating the second and therefore the body is null/empty. You could always pass the firstContentCachingRequestWrapperinto your method rather than creating a second instance.