此版本仍在开发中,尚未被视为稳定版。如需最新稳定版本,请使用 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>

从版本 7.1 开始,此端点支持 RestClient 配置。 基于 RestTemplate 的端点配置已弃用,并计划在未来的版本中移除。 要迁移现有的 RestTemplate 自定义功能,请使用 RestClient.create(restTemplate) 创建 RestClient,并在该端点上配置生成的客户端。 底层的 HTTP 客户端利用 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 出站网关之后用于某些路由逻辑。 您也可以使用 `` 将带有 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