Spring 使用 feign时设置header信息

Spring 使用 feign时设置header信息背景 之前使用 SpringBoot 项目 把一些使用 httpclient 的请求转为 使用 feign 方式

大家好,欢迎来到IT知识分享网。

一、背景:

之前使用 SpringBoot 项目,把一些使用 httpclient 的请求转为 使用 feign方式。但是遇到一个问题:个别请求是要设置header的。

接口如下:

@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; 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/90720.html

(0)
上一篇 2026-03-26 18:33
下一篇 2024-04-14 19:45

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信