如何配置int-http:outbound-gateway将请求头转为URL请求参数?
解决方案分析与修正
你的配置问题出在对<int-http:uri-variable>的误用以及参数表达式的错误引用上:
<int-http:uri-variable>是用来替换URL中的路径占位符(比如http://xxx/workflow/{testId}),而非生成查询参数(?testId=xxx)。- 你引用的
#requestParams并非当前上下文的有效变量,你的参数实际存储在请求头中,应该直接通过headers对象获取。
下面提供两种可行的修正方案:
方案一:直接拼接URL查询参数
通过url-expression直接将请求头中的参数拼接为URL的查询字符串,适合参数数量较少的场景:
<int:gateway id="requestGateway" default-request-channel="request.channel"> <!-- 若调用网关时已传入testId、userId请求头,此处default-header配置可省略 --> <int:default-header name="testId" expression="headers.testId" /> <int:default-header name="userId" expression="headers.userId" /> </int:gateway> <int-http:outbound-gateway id="driverWorkloadGateway" request-channel="request.channel" url-expression="headers.bstUrl + '?testId=' + headers.testId + '&userId=' + headers.userId" http-method="GET" expected-response-type="java.lang.String" charset="UTF-8" request-factory="httpComponentClientRequestFactory" mapped-request-headers="*" />
方案二:使用<int-http:request-parameter>标签(推荐)
Spring Integration专门提供了<int-http:request-parameter>标签用于设置URL查询参数,语义更清晰,维护性更好:
<int:gateway id="requestGateway" default-request-channel="request.channel"> <!-- 若调用网关时已传入testId、userId请求头,此处default-header配置可省略 --> <int:default-header name="testId" expression="headers.testId" /> <int:default-header name="userId" expression="headers.userId" /> </int:gateway> <int-http:outbound-gateway id="driverWorkloadGateway" request-channel="request.channel" url-expression="headers.bstUrl" http-method="GET" expected-response-type="java.lang.String" charset="UTF-8" request-factory="httpComponentClientRequestFactory" mapped-request-headers="*" > <int-http:request-parameter name="testId" expression="headers.testId"/> <int-http:request-parameter name="userId" expression="headers.userId"/> </int-http:outbound-gateway>
额外说明
- 若你在调用
requestGateway时已经明确传入了testId和userId请求头,网关配置中的<int:default-header>可以直接删除,避免冗余。 mapped-request-headers="*"会将所有请求头传递到外部服务,若不需要全部传递,可指定具体头名称(比如testId,userId,bstUrl),减少不必要的头传递。
内容的提问来源于stack exchange,提问作者KeepItSimple
相关产品推荐
相关产品推荐

