I’m trying to get request body of request and sending to database
Here is my lines of code :
@Component
public class CustomInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(CustomInterceptor.class);
private final LogStore logStore;
public CustomInterceptor(LogStore logStore) {
this.logStore = logStore;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Wrap the request with ContentCachingRequestWrapper
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
// Log request details
Log requestLog = new Log();
requestLog.setPath(wrappedRequest.getRequestURI());
requestLog.setMethod(wrappedRequest.getMethod());
String requestBody = getRequestBody(wrappedRequest);
requestLog.setRequestObject(requestBody);
// Save request log to database
logStore.save(requestLog);
return true; // Proceed with handler execution
}
private String getRequestBody(ContentCachingRequestWrapper request) {
byte[] buf = request.getContentAsByteArray();
if (buf.length > 0) {
return new String(buf, 0, buf.length, StandardCharsets.UTF_8);
}
return "";
}
}
But I always get an empty request body,even though I send a Post method with a JSON request body, what should I do to solve this problem ?
Thanks a lot
2
According to this thread: Get the POST request body from HttpServletRequest it is possible to get the requestBody like this:
String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
I tested this with your code and it should work.
Something seems to be wrong with your getRequestBody
method or with the ContentCachingRequestWrapper
that has certain conditions when to return the content.
1