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

使用Netflix DGS GraphQL Java Client时如何传递请求头?

DGS GraphQL Client 自定义请求头相关问题解答

疑问1:exec方法的headers参数来源与自定义头添加方式

exec方法的headers参数并非无意义,它有两个来源:

  1. 框架默认注入的标准头信息,比如Content-Type: application/json,这是GraphQL POST请求的必要头;
  2. 你调用executeQuery时传入的自定义请求头。

你之前只使用了无headers参数的executeQuery重载,所以没感知到这个参数的作用。要传递自定义头,直接用带headers参数的executeQuery重载版本即可,示例如下:

// 构造自定义请求头
Map<String, List<String>> customHeaders = new HashMap<>();
customHeaders.put("Authorization", Collections.singletonList("Bearer your-token"));
customHeaders.put("X-Request-ID", Collections.singletonList("unique-id-123"));

// 调用带headers参数的executeQuery重载
GraphQLResponse response = graphQLClient.executeQuery(request.serialize(), customHeaders);

此时自定义headers会被传入requestExecutor::exec的headers参数中,框架默认头也会自动合并进去,完全不需要重新创建RequestExecutor实例。

疑问2:请求头变化无需重建客户端,且可复用现有RequestExecutor

不需要每次请求头变化都创建新的CustomGraphQLClient实例。你只需要在每次调用executeQuery时传入不同的headers参数即可,客户端会自动把这些头传递给你的执行逻辑。

至于复用现有requestExecutor::exec实现,只需在创建CustomGraphQLClient时,在lambda里直接调用你的requestExecutor的exec方法,并把框架传入的url、headers、body参数原样传递进去,示例:

CustomGraphQLClient client = GraphQLClient.createCustom(hostUrl, (url, headers, body) -> {
    // 直接复用你已实现的requestExecutor
    return requestExecutor.exec(url, headers, body);
});

// 后续请求可灵活传入不同headers,无需重建客户端
Map<String, List<String>> headers1 = new HashMap<>();
headers1.put("Authorization", Collections.singletonList("Bearer token1"));
client.executeQuery(query1, headers1);

Map<String, List<String>> headers2 = new HashMap<>();
headers2.put("Authorization", Collections.singletonList("Bearer token2"));
client.executeQuery(query2, headers2);

这样既保留了你自己的RequestExecutor实现,又能灵活传递不同的请求头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:33:24