Reputation: 1754
I want to use this code to get the request and response payload:
https://gist.github.com/baberali/59ad73b2a1dcc5042e53f32585770df7
I tried this:
@RestController()
public class HomeController {
@PostMapping(value = "/v1")
public Response handleMessage(@RequestBody Transaction transaction, HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpServletRequest requestToCache = new ContentCachingRequestWrapper(request);
HttpServletResponse responseToCache = new ContentCachingResponseWrapper(response);
String requestData = getRequestData(requestToCache);
String responseData = getResponseData(responseToCache);
}
private 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;
}
private static String getResponseData(final HttpServletResponse response) throws IOException {
String payload = null;
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response,
ContentCachingResponseWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
wrapper.copyBodyToResponse();
}
}
return payload;
}
}
But when I print the result I get NULL. Do you know why the content is empty?
Upvotes: 0
Views: 801
Reputation: 5230
The code in sample you provide works as a filter (assuming response is already written). You are using controller method. In controller you'll be able to get the request. But response is something you need to write, but not read. Move this logic to filter chain.
Code to read request body in controller method:
@RestController()
public class HomeController {
@PostMapping(value = "/v1")
public Response handleMessage(@RequestBody String plainBody) throws Exception {
System.out.println("This is request body: " + plainBody);
}
}
Upvotes: 1