Skip to content

Instantly share code, notes, and snippets.

@Linkit123
Last active January 9, 2022 16:36
Show Gist options
  • Save Linkit123/78517f196fde66ceaaf86f9a5fb9a254 to your computer and use it in GitHub Desktop.
Save Linkit123/78517f196fde66ceaaf86f9a5fb9a254 to your computer and use it in GitHub Desktop.
package com.dvtt.demo.coredemo.interceptor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@Slf4j
@AllArgsConstructor
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
logRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
logResponse(response);
return response;
}
private void logRequest(HttpRequest request, byte[] body) throws IOException {
log.info("===========================request begin================================================");
log.info("URI : {}", request.getURI());
log.info("Method : {}", request.getMethod());
log.info("Headers : {}", request.getHeaders());
log.info("Request body: {}", new String(body, StandardCharsets.UTF_8));
log.info("==========================request end================================================");
}
private void logResponse(ClientHttpResponse response) throws IOException {
log.info("============================response begin==========================================");
log.info("Status code : {}", response.getStatusCode());
log.info("Status text : {}", response.getStatusText());
log.info("Headers : {}", response.getHeaders());
log.info("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
log.info("=======================response end=================================================");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment