HTTP 出站元件

本節描述了 Spring Integration 的 HTTP 出站元件。

使用 HttpRequestExecutingMessageHandler

要配置 HttpRequestExecutingMessageHandler,請編寫一個類似於以下的 bean 定義:

<bean id="httpOutbound"
  class="org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler">
  <constructor-arg value="https://: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="https://: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 客戶端,您可以注入它(如前所示)。

對於出站閘道器,由閘道器生成的回覆訊息包含請求訊息中存在的所有訊息頭。

使用 Cookie

出站閘道器上的 transfer-cookies 屬性提供了基本的 cookie 支援。當設定為 true(預設值為 false)時,從伺服器響應中收到的 Set-Cookie 頭將轉換為回覆訊息中的 Cookie。然後,此頭將用於後續傳送。這使得簡單的有狀態互動成為可能,例如以下內容:

...​→logonGateway→...​→doWorkGateway→...​→logoffGateway→...​

如果 transfer-cookiesfalse,則收到的任何 Set-Cookie 頭在回覆訊息中仍為 Set-Cookie,並在後續傳送時被丟棄。

空響應正文

HTTP 是一種請求-響應協議。然而,響應可能沒有正文,只有頭。在這種情況下,無論提供了任何 expected-response-typeHttpRequestExecutingMessageHandler 都會生成一個負載為 org.springframework.http.ResponseEntity 的回覆 Message。根據 HTTP RFC 狀態碼定義,有許多狀態碼規定響應不得包含訊息正文(例如,204 No Content)。也有一些情況是,對相同 URL 的呼叫可能返回或不返回響應正文。例如,對 HTTP 資源的第一個請求返回內容,但第二個請求不返回內容(返回 304 Not Modified)。然而,在所有情況下,http_statusCode 訊息頭都會被填充。這可以在 HTTP 出站閘道器之後的某些路由邏輯中使用。您還可以使用 將包含 ResponseEntity 的訊息路由到與包含正文的響應訊息不同的流。

expected-response-type

除了前面關於空響應正文的說明之外,如果響應確實包含正文,則必須提供適當的 expected-response-type 屬性,否則,您將再次收到一個沒有正文的 ResponseEntityexpected-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

© . This site is unofficial and not affiliated with VMware.