Bkauf Bkauf -4 years ago 300
reST (reStructuredText) Question

Spring ClientHttpRequestInterceptor request/response empty

I would like to grab the REST request and response bodies for logging purposes in my application.

I currently have a loggingRequestInterceptor class that implements ClientHttpRequestInterceptor, very similar to the answer by sofiene here.

I have then added this interceptor as a property within my Rest Template in my spring configuration.

My code is shown below:

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

private static final Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

ClientHttpResponse response = execution.execute(request, body);

response = log(request, body, response);

return response;
}

private ClientHttpResponse log(final HttpRequest request, final byte[] body, final ClientHttpResponse response) throws IOException {
final ClientHttpResponse responseCopy = new BufferingClientHttpResponseWrapper(response);
StringBuilder builder = new StringBuilder();
builder.append("Method: ").append(request.getMethod().toString());
builder.append("URI: ").append(request.getURI().toString());
builder.append("Request Body: ").append(new String(body,"UTF-8"));
builder.append("Response body: ").append(convertStreamToString(responseCopy.getBody()));
logger.info(builder.toString());
return responseCopy;
}
}


Spring Property on my RestTemplate:

<property name="interceptors">
<list>
<bean class="com.company.projectName.service.api.rest.io.impl.LoggingRequestInterceptor" />
</list>
</property>


However, on all of my rest calls I log the Method and URI, but the body and the response body are empty. What is the proper way to grab the bodies from the request and the response in order to allow my application to log this information.

Answer Source

Solution: First, the request body was blank because this is a GET method. Second, I also needed to log the ResponseStatusCode as I was receiving a status of 204 which is No Content, thus resulting in a blank response body.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download