spring-cloud-config feign 设置 header 请求头

最近在使用 feign-clien 的时候 需要设置请求头,遇到一些小问题,于是就度娘了一下说是按照下面方式设置:

public interface XXService {
    @GetMapping("/xx")
    @Headers({"Content-Type: application/json","Accept: application/json"})
    String send(String params);
}

调试了一下发现根本没生效。。。

于是就看了下源码发现Header信息是从@RequestMapping 里面去取的,所以改了一下配置 如下:

public interface XXService {
    @GetMapping(value = "/xx", headers = {"Content-Type=application/json","Accept=application/json"})
    String send(String params);
}

注意: Headers 里面的连接符写法和上面不一样,上面使用的是冒号,下面使用的是等于号,要使用等于号!

还有另外一种配置Header方式 就是传参的方式 如下:

public interface XXService {
    @GetMapping("/xx")
    String send(@RequestHeader("Content-Type")String contentType);
}

如果需要对feign 做统一处理可以使用feign拦截器 做处理。

全局处理 使用 @Configuration 配置

@Configuration
public class FeignConfiguration 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);
            }
        }
    }
}

指定单个接口类的处理

@FeignClient(name = "Xserver", configuration = FeignConfiguration.class)
public interface XServer{
}

你可能感兴趣的:(spring-cloud)