如需使用最新稳定版本,请使用 Spring Integration 7.0.4spring-doc.cadn.net.cn

HTTP 出站组件

本节介绍 Spring Integration 的 HTTP 出站组件。spring-doc.cadn.net.cn

使用HttpRequestExecutingMessageHandler

要配置HttpRequestExecutingMessageHandler,请编写如下所示的 Bean 定义:spring-doc.cadn.net.cn

<bean id="httpOutbound"
  class="org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler">
  <constructor-arg value="http://localhost:8080/example" />
  <property name="outputChannel" ref="responseChannel" />
</bean>

此 Bean 定义通过将 HTTP 请求委托给 RestTemplate 来运行。 该模板随后将请求委托给一系列 HttpMessageConverter 实例,以从 Message 有效负载生成 HTTP 请求体。 正如以下示例所示,您也可以配置这些转换器以及要使用的 ClientHttpRequestFactory 实例:spring-doc.cadn.net.cn

<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,您可以像之前所示那样注入它。spring-doc.cadn.net.cn

对于出站网关,网关生成的回复消息包含请求消息中存在的所有消息头。

使用 Cookie

基本的 Cookie 支持由出站网关上的 transfer-cookies 属性提供。 当设置为 true(默认为 false)时,从服务器在响应中接收到的 Set-Cookie 头将被转换为回复消息中的 Cookie。 随后,该头将在后续发送中使用。 这实现了简单的有状态交互,如下所示:spring-doc.cadn.net.cn

…​→logonGateway→…​→doWorkGateway→…​→logoffGateway→…​spring-doc.cadn.net.cn

如果 transfer-cookiesfalse,则任何接收到的 Set-Cookie 标头在回复消息中保持为 Set-Cookie,并在后续发送时被丢弃。spring-doc.cadn.net.cn

空响应体

HTTP 是一种请求 - 响应协议。 然而,响应可能没有主体(body),仅包含头部(headers)。 在这种情况下,HttpRequestExecutingMessageHandler会产生一个回复Message,其负载(payload)为org.springframework.http.ResponseEntity,无论提供的expected-response-type是什么。 根据HTTP RFC 状态码定义,有许多状态码强制要求响应不得包含消息主体(例如,204 No Content)。 也存在这样的情况:对同一 URL 的调用可能会有或没有响应主体。 例如,对 HTTP 资源的第一次请求返回内容,但第二次请求则不返回(返回304 Not Modified)。 然而在所有情况下,http_statusCode消息头都会被填充。 这可以在 HTTP 出站网关之后的某些路由逻辑中使用。 您也可以使用`<payload-type-router/>`将具有ResponseEntity的消息路由到与带有主体的响应不同的流程中。spring-doc.cadn.net.cn

expected-response-type

关于前面提到的空响应体,如果响应确实包含一个体,则必须提供适当的expected-response-type属性,否则您将收到一个没有体的ResponseEntityexpected-response-type必须与响应中的(配置的或默认的)HttpMessageConverter实例以及Content-Type头兼容。 这可以是一个抽象类,甚至是一个接口(例如,当使用 Java 序列化时是java.io.Serializable,以及Content-Type: application/x-java-serialized-object)。spring-doc.cadn.net.cn

从版本 5.5 开始,HttpRequestExecutingMessageHandler 暴露了一个 extractResponseBody 标志(默认为 true),用于仅返回响应体,或无论提供的 expectedResponseType 如何,都返回整个 ResponseEntity 作为回复消息负载。 如果 ResponseEntity 中不存在响应体,则忽略此标志并返回整个 ResponseEntityspring-doc.cadn.net.cn