简体   繁体   中英

Custom interceptor in Spring Boot [ADD HTTP REQUEST HEADER]

I trying to create a custom interceptor in a spring boot app for add a header in each http request.

for example:
POSTMAN --[GET: http://some_url] --> INTERCEPTOR -- [ADD HEADER "ID"] --> RestController [GET HEADER ID].

I tried to create an interceptor like this

@Component
public class LogRequestHandler implements ClientHttpRequestInterceptor {
private final Logger log = LoggerFactory.getLogger(LogRequestHandler.class);

  @Override
  public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, 
                ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    String trackingId = RandomStringUtils.randomAlphanumeric(8);
    long timestamp = ZonedDateTime.now(ZoneOffset.UTC).toInstant().toEpochMilli();
    log.info("Request [{}] {} {}", trackingId, httpRequest.getMethod(), httpRequest.getURI());
    httpRequest.getHeaders().add("TRACKING_ID", trackingId);
    httpRequest.getHeaders().add("TIMESTAMP", String.valueOf(timestamp));
    return clientHttpRequestExecution.execute(httpRequest, bytes);
  }
} 

but i don't know how add this to spring configuration :((
Can someone confirm if my approach it's correct or suggest other idea?
Thx in advance.

in spring WebMvcConfigurerAdapter you have the method dedicated for that

public void addInterceptors(InterceptorRegistry registry)

so you can do something like this:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired 
  HandlerInterceptor yourInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(yourInterceptor);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM