You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Feign Client中设置请求Cookie请求头?

FeignClient 设置Cookie请求头的正确方式

你之前使用@CookieValue失败的原因是:这个注解在Feign接口中的作用是从请求中提取Cookie参数,而非向请求头中添加Cookie。以下几种方法可以实现你需要的Cookie: CUSTOM_COOKIE={VALUE}格式:

方法1:手动构造Cookie请求头

直接通过@RequestHeader传入完整的Cookie字符串,完全匹配Postman的格式:

@FeignClient(value = "petShopApi", url="http://localhost:8080/pets")
public interface PetShopFeignClient {

    @GetMapping("/dogs")
    Response getResponse(@RequestHeader("Cookie") String cookieHeader);
}

调用时传入"CUSTOM_COOKIE=你的token值"即可。

方法2:使用Feign原生@Header注解动态替换

利用Feign的@Header注解(注意是feign.Header而非Spring的注解),固定Cookie键,仅传入token值:

import feign.Header;
import feign.Param;

@FeignClient(value = "petShopApi", url="http://localhost:8080/pets")
public interface PetShopFeignClient {

    @GetMapping("/dogs")
    @Header("Cookie: CUSTOM_COOKIE={token}")
    Response getResponse(@Param("token") String token);
}

调用时直接传入token值,Feign会自动替换占位符生成正确的Cookie头。

方法3:通过请求拦截器全局/局部设置

如果多个接口需要统一设置Cookie,可使用Feign的RequestInterceptor:

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PetShopFeignConfig {

    @Bean
    public RequestInterceptor cookieInterceptor() {
        return template -> {
            // 可根据业务逻辑动态获取token,比如从上下文、配置文件等
            String token = "你的动态token值";
            template.header("Cookie", "CUSTOM_COOKIE=" + token);
        };
    }
}

然后在FeignClient中指定该配置:

@FeignClient(value = "petShopApi", url="http://localhost:8080/pets", configuration = PetShopFeignConfig.class)
public interface PetShopFeignClient {

    @GetMapping("/dogs")
    Response getResponse();
}

内容的提问来源于stack exchange,提问作者2dor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:15:53