使用@FeignClient时如何传递多个RequestHeader

时间:2018-08-23 13:45:20

标签: spring-boot spring-cloud-feign feign

我需要使用 @FeignClient

传递多个请求标头

当它的一个类型为String的标头时, @RequestHeader 可以正常工作,但是在启动弹簧启动时,多次获得 RequestHeader.value()在参数0上为空错误。

           @RequestMapping(value="/*********employees", method= RequestMethod.GET , consumes = MediaType.APPLICATION_JSON_VALUE)
EmployeeData fetchWorkdayEmployeess(@RequestHeader Map<String, Object> headers);

以及我尝试使用@HeaderMap

    @RequestMapping(value="/*********employees", method= RequestMethod.GET , consumes = MediaType.APPLICATION_JSON_VALUE)
EmployeeData fetchWorkdayEmployeess(@HeaderMap Map<String, Object> headers);

我还尝试将多个@RequestHeaders作为参数传递,但似乎不起作用

1 个答案:

答案 0 :(得分:0)

我需要使用自定义的 RequestInterceptor

@Configuration
class FeignCustomHeaderConfig {

    @Bean
    public CSODHeaderAuthRequestInterceptor basicAuthRequestInterceptor() {
        try {
            return new HeaderAuthRequestInterceptor(token_map);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
        }
        return new CSODHeaderAuthRequestInterceptor(null);
    }

    class HeaderAuthRequestInterceptor implements RequestInterceptor {

        //Expensive OAuth2 flow logic
        private HashMap<String, String> tokenMap;

        public HeaderAuthRequestInterceptor(HashMap<String, String> tokenMap) {
            this.tokenMap = tokenMap;
        }

        @Override
        public void apply(RequestTemplate requestTemplate) {
            if(tokenMap == null)
                return;
            requestTemplate.header(key1, tokenMap.get(key1));
            requestTemplate.header(key2, tokenMap.get(key2));
            ....
        }
    }

然后将配置类添加到您的伪装客户端

@FeignClient(name="....",url="...",configuration=FeignCustomHeaderConfig.class)

Reference link here :