23 Nisan 2023 Pazar

SpringMVC RestTemplate.setInterceptors metodu

Örnek
Şöyle yaparız.
List<ClientHttpRequestInterceptor> interceptors = ...;
restTemplate.setInterceptors(interceptors);
Örnek
Şöyle yaparız
@Configuration
public class RestTemplateConfig {

  @Bean
  public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new
        SimpleClientHttpRequestFactory()));

    restTemplate.setInterceptors(Collections.singletonList(new RestTemplateFilter()));
    return restTemplate;
  }
}
Açıklaması şöyle
If we don’t initialise Rest Template with the BufferingClientHttpRequestFactory class, we will get an OK response to our requests but we will get a null value for the response body.
interceptor şöyledir
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

public class RestTemplateFilter implements ClientHttpRequestInterceptor {
  private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateFilter.class);

  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body,
      ClientHttpRequestExecution execution) throws IOException {

    LOGGER.info("RestTemplate does a http/s to - {} with HTTP Method : {}", 
      request.getURI(), request.getMethodValue());

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

    if (response.getStatusCode().is4xxClientError() || response.getStatusCode()
        .is5xxServerError()) {
      LOGGER.error("RestTemplate received a bad response from : {} 
        - with response status : {} and body : {} ",
      request.getURI(), response.getRawStatusCode(), 
        new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8));
    } else {
      LOGGER.info("RestTemplate received a good response from : {}
        - with response status {}",
          request.getURI(),
          response.getRawStatusCode());
    }
    return response;
  }
}
Açıklaması şöyle
In intercept method, the HTTP request is logged, including the HTTP method, URI and request body (if any), as well as the HTTP response, including status code, status text and response body (if any).

Hiç yorum yok:

Yorum Gönder