I have created a class name as HttpInterceptor
which implements ClientHttpRequestInterceptor
. The purpose of this class is to intercept the resttemplate
calls, then override the intercept method. During execution, I am unable to log the request body. However, there is a request body which is sent from the front end.
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
String requestBody = "";
String url = request.getURI().toString();
ClientHttpResponse response = null;
Date timeIn = new Date();
String responseBody = "";
// I have also try new String(body, "UTF-8") and many others.
requestBody = new String(body, Charset.forName("UTF-8"));
logger.info("=============================REQUEST BEGIN==============================================");
logger.info("URI :" + url);
logger.info("Method :" + request.getMethod());
logger.info("Headers :" + request.getHeaders());
logger.info("Request body:" + requestBody);
logger.info("=============================REQUEST END================================================");
response = execution.execute(request, body);
responseBody = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
//new String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"))
logger.info("=============================RESPONSE BEGIN=============================================");
logger.info("Status code : " + response.getStatusCode());
logger.info("Status text : " + response.getStatusText());
logger.info("Headers : " + response.getHeaders());
logger.info("Response body: " + responseBody);
logger.info("=============================RESPONSE END===============================================");
return response;
}
The rest template is initialized like this:
RestTemplate restTemplate = new RestTemplate(
new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
restTemplate.setInterceptors(Collections
.singletonList(new HttpInterceptor()));
I have also found a similar question on StackOverflow Why my custom ClientHttpRequestInterceptor with an empty response , but it's completely different from what I want.