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

如何在Micronaut声明式客户端用Map传递多个不同请求头?

在Micronaut声明式客户端中传递动态名称的请求头

你可以通过以下方式实现传递任意名称和值的请求头:

核心方案:使用@Header修饰Map参数

在声明式客户端的方法中,直接用@Header注解修饰Map<String, String>类型的参数,Map中的每一组键值对会自动转为请求头(键作为头名称,值作为头内容),无需提前固定任何头名称。

代码示例

1. 定义声明式客户端接口

import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.client.annotation.Client;

@Client("https://your-target-api.com")
public interface DynamicHeaderClient {

    @Get("/target-endpoint")
    HttpResponse<String> fetchResource(@Header Map<String, String> dynamicHeaders);
}

2. 调用客户端并传入动态请求头

import java.util.HashMap;
import java.util.Map;

// 构建任意名称的请求头Map
Map<String, String> dynamicHeaders = new HashMap<>();
dynamicHeaders.put("X-Custom-Header-A", "value-a");
dynamicHeaders.put("Authorization", "Bearer your-token");
dynamicHeaders.put("X-Request-ID", "uuid-12345");

// 调用客户端接口
HttpResponse<String> response = dynamicHeaderClient.fetchResource(dynamicHeaders);

混合固定头与动态头

如果需要部分请求头固定、部分动态,可以同时使用静态@Header注解和动态Map参数:

@Get("/target-endpoint")
@Header(name = "Content-Type", value = "application/json")
HttpResponse<String> fetchResource(@Header Map<String, String> dynamicHeaders);

这种方式下,Content-Type会被固定为application/json,同时Map中的所有键值对会被额外添加为请求头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:55:02