Fegin和RestTemplate添加全局请求头

Fegin添加全局请求头

  • 实现RequestInterceptor接口

/**
* 实现RequestInterceptor接口的apply方法
*/
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);

            }
        }
    }
}
  • @FeginClient注释里configuration所填入的类文件中添加上面的拦截器

    比如

    // configuration指定的类为FeignConfig
    
    @FeignClient(name = "${TinyConfigServiceName}",path="/config",configuration = FeignConfig.class)
    
    • 在FeignConfig类中添加拦截器

      @Configuration
      public class FeignConfig {
          @Bean
          public RequestInterceptor requestInterceptor(){
              return new FeignRequestInterceptor();
          }
      }
      

RestTemplate添加全局请求头

  • 编写拦截器,实现ClientHttpRequestInterceptor接口的intercept方法

    public class MyInterceptor implements ClientHttpRequestInterceptor {
        @Override
        public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
            HttpHeaders httpHeaders=httpRequest.getHeaders();
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    httpHeaders.add(name, values);
                }
            }
            return clientHttpRequestExecution.execute(httpRequest,bytes);
        }
    }
    
  • 在springboot的启动类里添加RestTemplate

    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        //ioc添加RestTemplate
        @Bean
        public RestTemplate restTemplate(){
            MyInterceptor myInterceptor=new MyInterceptor();
            RestTemplate restTemplate=new RestTemplate();
            restTemplate.setInterceptors(Collections.singletonList(myInterceptor));
            return restTemplate;
        }
    
    }