欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Spring 使用 feign时设置header信息的操作

时间:2022-05-28 08:47:14|栏目:JAVA代码|点击:

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;

Feign动态设置Header

Feign调用接口:

/**
 * @author Liangzhifeng
 * date: 2018/9/13
 */
public interface UserInfoFeignClient {

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    @RequestMapping(value = "/user/info/1.0", method = RequestMethod.POST)
    Object getUserInfoByToken(@RequestParam("token") String token);
}

/**
 * @author Liangzhifeng
 * date: 2018/9/15
 */
@Component
public class AuthorityConfig {

    /**
     * 授权信息Header的key
     */
    public static final String OAUTH_KEY = "token";

    /**
     * 授权信息Header的值的前缀
     */
    public static final String OAUTH_VALUE_PREFIX = "Bearer ";

	// GlobalConstant.AUTHORITY_SERVICE_LINK  : 服务的名称

    @Autowired
    private Client client;

    public UserInfoFeignClient userInfoFeignClient(String token) {
        UserInfoFeignClient authorityServiceLoginInvoker = Feign.builder().client(client)
                .encoder(new GsonEncoder())
                .decoder(new GsonDecoder())
                .contract(new SpringMvcContract())
                .requestInterceptor(template -> template.header(OAUTH_KEY, OAUTH_VALUE_PREFIX + token))
                .target(UserInfoFeignClient.class, GlobalConstant.AUTHORITY_SERVICE_LINK);
        return authorityServiceLoginInvoker;
    }
}

接口调用:

@Autowired
private AuthorityConfig authorityConfig;

/**
 * 根据token获取用户信息
 *
 * @param token 用户登录的授权token
 * @return 用户信息JSON
 */
public Object getUserInfo(String token) {
    try {
        Object userInfo = authorityConfig.userInfoFeignClient(token).getUserInfoByToken(token);
        return userInfo;
    } catch (Exception e) {
        log.info("获取用户信息异常", e);
        return null;
    }
}

上一篇:Springcloud-nacos实现配置和注册中心的方法

栏    目:JAVA代码

下一篇:没有了

本文标题:Spring 使用 feign时设置header信息的操作

本文地址:http://www.codeinn.net/misctech/203113.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有