Spring使⽤feign时设置header信息
最近使⽤ SpringBoot 项⽬,把⼀些 http 请求转为使⽤ feign⽅式。但是遇到⼀个问题:个别请求是要设置header的。
springboot其实就是spring于是,查看官⽅⽂档和博客,⼤致推荐两种⽅式。也可能是我没看明⽩官⽅⽂档。
接⼝如下:
@FeignClient(url = "XX_url", value = "XXService")
public interface XXService {
@RequestMapping(value = "/xx", method = RequestMethod.POST)
@Headers({"Content-Type: application/json","Accept: application/json"})
String sendDing(String params);
}
1. 使⽤Headers注解。直接在请求上或者在类上添加
这种⽅式经过尝试,没有作⽤。暂时不清楚原因。
2. 通过实现RequestInterceptor接⼝,完成对所有的Feign请求,设置Header
@Component
public class FeginClientConfig {
@Bean
public RequestInterceptor headerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
// ⼩⽰例,没什么卵⽤
requestTemplate.header("Content-Type", "application/json");
}
};
}
@Bean
public Logger.Level level() {
return Logger.Level.FULL;
}
}
  这种⽅式,是针对所有feign请求进⾏拦截,设置Header,不适于我的需求。
后来发现其实我的思路⾛偏了。咨询了⼀个同事,既然使⽤的是RequestMapping注解。那么直接使⽤RequestMapping注解的header属性就可以了。如下:
@RequestMapping(value = "/xx", method = RequestMethod.POST, headers = {"content-type=application/x-www-form-urlencoded"})
  有⼀点需要注意:content-type=application/x-www-form-urlencoded。此时,⽅法⾥接收的参数,就不能直接是⼀个对象(Map等)。不然还是会默认
content-type为 application/json.
@RequestMapping(value = "/xx", method = RequestMethod.POST, headers = {"content-type=application/x-www-form-urlencoded"})
String login(@RequestParam("username") String username, @RequestParam("password") String password;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。