背景
在进行Spring Cloud 的编码中,需要调用远程服务接口,使用了Feign,但是该远程接口需要传递Cookie,默认的Feign 无法传输Cookie。
解决方案
以下方案来源互联网整理和测试。
请求头设置
@Configuration
@Slf4j
public class FeignHeadConfiguration {
/**
* 配置cookies
*
* @return
*/
@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attrs != null) {
HttpServletRequest request = attrs.getRequest();
// 如果在Cookie内通过如下方式取
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
requestTemplate.header(cookie.getName(), cookie.getValue());
}
} else {
log.warn("获取Cookie失败!");
}
//获取header 信息
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = request.<