feign微服务调用携带浏览器信息(header、cookie)

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@Configuration
public class FeignConfiguration {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();
                    Enumeration<String> attributeNames = request.getHeaderNames();
                    if (attributeNames != null) {
                        while (attributeNames.hasMoreElements()) {
                            String name = attributeNames.nextElement();
                            String value = request.getHeader(name);
                            requestTemplate.header(name,value);

                        }
                    }
                }
            }
        };
    }
}

 

posted @ 2021-09-02 22:36  it_bky  阅读(1453)  评论(0编辑  收藏  举报