SpringBoot Feign内部调用时自动带上请求头信息(header)
Posted 我叫白小飞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot Feign内部调用时自动带上请求头信息(header)相关的知识,希望对你有一定的参考价值。
我们在项目中单独使用feign时,有时候需要带上header,但是,手动添加header注释,或者在mapping里边写上header太麻烦,需要从请求里边取出来,然后再放到feign里边,下边介绍一种简单的方式:
@Configuration
public class FeignConf implements RequestInterceptor
private final ObjectFactory<HttpMessageConverters> messageConverters;
public FeignConf(ObjectFactory<HttpMessageConverters> messageConverters)
this.messageConverters = messageConverters;
@Bean
@Primary
@Scope("prototype")
public Encoder feignEncoder()
return new SpringFormEncoder(new SpringEncoder(messageConverters));
@Bean
public Retryer feignRetarder()
return new Retryer.Default(100,SECONDS.toMillis(1),5);
@Bean
Logger.Level feignLoggerLevel()
return Logger.Level.FULL;
@Override
public void apply(RequestTemplate template)
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null)
while (headerNames.hasMoreElements())
String name = headerNames.nextElement();
String values = request.getHeader(name);
template.header(name, values);
Enumeration<String> bodyNames = request.getParameterNames();
// 主要的就是以下这段代码,是将当前请求中的header取出来,放到第三方请求中去
Request.Body body = template.requestBody();
Map<String,Object> map = new HashMap<>(16);
if (bodyNames != null)
while (bodyNames.hasMoreElements())
String name = bodyNames.nextElement();
String values = request.getParameter(name);
map.put(name,values);
body.expand(map);
template.body(body);
以上是关于SpringBoot Feign内部调用时自动带上请求头信息(header)的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot Feign内部调用时自动带上请求头信息(header)
Spring Boot 2 - 自动装配服务时对 Feign 客户端的不满意依赖