LoggingRequestInterceptor.java
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
final static Logger LOGGER = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
final static String CHARSET = "UTF-8";
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
LOGGER.info(
"===========================request begin=============================================\n"+
" > URI : {}\n"+
" > Method : {}\n"+
" > Headers : {}\n"+
" > Request body: {}\n"+
"==========================request end================================================",
request.getURI(), request.getMethod(), request.getHeaders(), new String(body, CHARSET));
}
private void traceResponse(ClientHttpResponse response) throws IOException {
StringBuilder inputStringBuilder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), CHARSET));) {
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
}
LOGGER.info(
"============================response begin==========================================\n"+
" < Status code : {}\n"+
" < Status text : {}\n"+
" < Headers : {}\n"+
" < Response body: {}\n"+
"=======================response end=================================================",
response.getStatusCode(), response.getStatusText(), response.getHeaders(), inputStringBuilder.toString());
}
}
RestTemplateConfiguration.java
@Configuration
public class RestTemplateConfiguration {
@Value("${rest.template.debug:false}")
private boolean debugRestTemplate;
@Bean(destroyMethod = "close")
public CloseableHttpClient closeableHttpClient() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(config.getProperty("custom.connection_pool_size", Integer.class, 2147483647));
connectionManager.setDefaultMaxPerRoute(config.getProperty("custom.connection_pool_size.per_route", Integer.class, 256));
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(config.getProperty("custom.socket_timeout", Integer.class, 30000))
.setConnectTimeout(config.getProperty("custom.connection_timeout", Integer.class, 120000))
.setCookieSpec(CookieSpecs.IGNORE_COOKIES) // because we get cookies directly from header
.build();
CloseableHttpClient apacheHttpClient = HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy())
.build();
return apacheHttpClient;
}
private RestTemplate build(Supplier<RestTemplate> usualRestClient, Supplier<RestTemplate> loggingRestClient) {
RestTemplate restTemplate;
if (debugRestTemplate) {
restTemplate = loggingRestClient.get();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new LoggingRequestInterceptor());
restTemplate.setInterceptors(interceptors);
} else {
restTemplate = usualRestClient.get();
}
return restTemplate;
}
@Bean
public RestTemplate noErrorRestTemplate() {
HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpComponentsClientHttpRequestFactory.setHttpClient(closeableHttpClient());
RestTemplate restTemplate = build(
() -> new RestTemplate(httpComponentsClientHttpRequestFactory),
() -> new RestTemplate(new BufferingClientHttpRequestFactory(httpComponentsClientHttpRequestFactory))
);
restTemplate.setErrorHandler(new ResponseErrorHandler(){
@Override
public boolean hasError(ClientHttpResponse ignore) {
return false;
}
@Override
public void handleError(ClientHttpResponse ignore) { }
});
return restTemplate;
}
}
tags: java, spring