JAVA使用feign调用传递header的解决方法,亲测有效

创建一个类用来配置feign调用时传递header的应用代码

package com.dimp.mobile.report.feign.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author  longmaolin
 * @description 解决feign组件来调用服务之间传递token问题
 * @createTime  2020/06/11
 */
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //仅仅添加token,和下面的逻辑代码二选其一
        requestTemplate.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));

//        //传递header里面所有内容
//        Enumeration headerNames = request.getHeaderNames();
//        if (headerNames != null) {
//            while (headerNames.hasMoreElements()) {
//                String name = headerNames.nextElement();
//                String values = request.getHeader(name);
//                requestTemplate.header(name, values);
//            }
//        }

    }
}

其次在具体的调用feign接口配置中配置一下configuration属性为刚才编写的配置类即可

@FeignClient(name = "report", configuration = FeignConfig.class)
public interface ReportFeign {

    @RequestMapping("/report/comment/organizationTree")
    public ResultDTO getOrganizationOfUsers();  //获取默认组织维度树
}

亲测有效。

你可能感兴趣的:(spring,java)