Spring Integration DSL中如何为outboundGateway添加请求头?
Hey there! Let's sort out that missing request header setup for your HTTP outbound gateway. There are a couple of straightforward ways to add your required headers (Accept, Content-Type, and Client-Id) to the request:
Approach 1: Enrich Message Headers Before the Gateway
This is the simplest method for static header values. Use .enrichHeaders() to attach the needed headers to your message, and the outbound gateway will automatically map these message headers to HTTP request headers (the default header mapper handles standard headers and supports custom ones properly):
.enrichHeaders(headersSpec -> headersSpec .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .header("Client-Id", "test")) .handle(Http.outboundGateway("localhost:8080/search") .httpMethod(HttpMethod.GET) .expectedResponseType(Order.class))
Approach 2: Customize the Header Mapper
If you need more granular control (like dynamic header values or strict header filtering), create a custom DefaultHttpHeaderMapper and attach it directly to the outbound gateway:
// Create and configure the header mapper DefaultHttpHeaderMapper headerMapper = DefaultHttpHeaderMapper.outboundMapper(); // Define which headers should be included in the outbound request headerMapper.setOutboundHeaderNames( new String[]{HttpHeaders.ACCEPT, HttpHeaders.CONTENT_TYPE, "Client-Id"}); // Set fixed values for your target headers headerMapper.setHeaderValueCallback(HttpHeaders.ACCEPT, msgHeaders -> MediaType.APPLICATION_JSON_VALUE); headerMapper.setHeaderValueCallback(HttpHeaders.CONTENT_TYPE, msgHeaders -> MediaType.APPLICATION_JSON_VALUE); headerMapper.setHeaderValueCallback("Client-Id", msgHeaders -> "test"); // Attach the custom mapper to your outbound gateway .handle(Http.outboundGateway("localhost:8080/search") .httpMethod(HttpMethod.GET) .expectedResponseType(Order.class) .headerMapper(headerMapper))
Quick Notes:
- For dynamic header values (e.g., pulling data from the message payload or attributes), you can use SpEL expressions in
.enrichHeaders()like this:.header("Client-Id", "#root.payload.clientId") - The default
DefaultHttpHeaderMapperincludes most standard HTTP headers out of the box. For custom headers likeClient-Id, just ensure they're added to theoutboundHeaderNameslist if you go with Approach 2.
内容的提问来源于stack exchange,提问作者nagendra

