• Spring 使用 feign时设置header信息


    最近使用 SpringBoot 项目,把一些 http 请求转为 使用 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;
    

      

  • 相关阅读:
    【转载】C/C++预处理器
    【转载】C/C++内存管理详解
    Spring知识点整理
    Hibernate知识点整理
    MyBatis知识点整理
    数据可视化(三)- Seaborn简易入门
    数据可视化(二)
    数据可视化(一)-Matplotlib简易入门
    Pandas之容易让人混淆的行选择和列选择
    Pandas简易入门(四)
  • 原文地址:https://www.cnblogs.com/hui-run/p/8969702.html
Copyright © 2020-2023  润新知