HTTP 出站组件
本节介绍 Spring Integration 的 HTTP 出站组件。
使用 HttpRequestExecutingMessageHandler
要配置 HttpRequestExecutingMessageHandler,请编写类似以下内容的 Bean 定义:
<bean id="httpOutbound"
class="org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler">
<constructor-arg value="http://localhost:8080/example" />
<property name="outputChannel" ref="responseChannel" />
</bean>
该bean定义通过委托给RestTemplate来执行HTTP请求。该模板又委托给一系列HttpMessageConverter实例,以从Message负载生成HTTP请求体。您可以配置这些转换器以及要使用的ClientHttpRequestFactory实例,如下例所示:
<bean id="httpOutbound"
class="org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler">
<constructor-arg value="http://localhost:8080/example" />
<property name="outputChannel" ref="responseChannel" />
<property name="messageConverters" ref="messageConverterList" />
<property name="requestFactory" ref="customRequestFactory" />
</bean>
默认情况下,HTTP 请求是通过 SimpleClientHttpRequestFactory 的实例生成的,该实例使用 JDK 的 HttpURLConnection。同时,也支持通过 CommonsClientHttpRequestFactory 使用 Apache Commons HTTP Client,你可以注入它(如前文所示)。
对于出站网关,网关生成的回复消息包含请求消息中存在的所有消息头。
使用 Cookie
基本的 Cookie 支持通过出站网关的 transfer-cookies 属性提供。当设置为 true(默认为 false)时,从服务器响应中收到的 Set-Cookie 标头会在回复消息中转换为 Cookie。随后发送时会使用此标头。这使得简单的有状态交互成为可能,例如:
…→logonGateway→…→doWorkGateway→…→logoffGateway→…
如果 transfer-cookies 为 false,接收到的任何 Set-Cookie 头在回复消息中仍保持为 Set-Cookie,并在后续发送时被丢弃。
空响应体
HTTP 是一种请求-响应协议。然而,响应可能没有正文,只有头部信息。在这种情况下,无论提供了何种 expected-response-type,HttpRequestExecutingMessageHandler 都会生成一个有效负载为 org.springframework.http.ResponseEntity 的回复 Message。根据 HTTP RFC 状态码定义,有许多状态码规定响应不得包含消息体(例如,204 No Content)。也存在对同一 URL 的调用可能返回也可能不返回响应体的情况。例如,对 HTTP 资源的第一次请求返回内容,但第二次不返回(返回 304 Not Modified)。然而,在所有情况下,http_statusCode 消息头都会被填充。这可以在 HTTP 出站网关之后的一些路由逻辑中使用。你也可以使用 \<payload-type-router/> 将带有 ResponseEntity 的消息路由到与带有正文的响应不同的流中。
expected-response-type
继前文关于空响应体的说明,如果响应确实包含响应体,你必须提供一个合适的 expected-response-type 属性,否则,你将再次收到一个没有响应体的 ResponseEntity。expected-response-type 必须与(已配置或默认的)HttpMessageConverter 实例以及响应中的 Content-Type 头部兼容。它可以是一个抽象类,甚至是一个接口(例如,当你使用 Java 序列化且 Content-Type: application/x-java-serialized-object 时,可以使用 java.io.Serializable)。
从5.5版本开始,HttpRequestExecutingMessageHandler 暴露了一个 extractResponseBody 标志(默认为 true),用于仅返回响应体,或将整个 ResponseEntity 作为回复消息的有效负载返回,这与提供的 expectedResponseType 无关。如果 ResponseEntity 中不存在响应体,则忽略此标志并返回整个 ResponseEntity。