Documentation for a newer release is available. View Latest

Adding Headers to TransportMessages

How do I add headers to an outbound message?

This Connector example shows how you can add any number of headers to messages sent by a SendingConnector. Headers are created during conversion of a target type into a TransportMessage stage, as described in Stages.

Implementing a SendTransportMessageConverter

The component that performs the transformation into a TransportMessage is called a SendTransportMessageConverter. To see how to register your converter with a connector, please see this getting started page.

Below is a sample converter that conditionally creates a few headers and adds them to the transport message:

SendTransportMessageConverter<YourTargetType> converter() {
    return toSend -> {
        MessageHeaders headers = /*condition*/
            ? new MessageHeaders("foo", "bar") (1)
            : new MessageHeaders(Map.of("foo", "bar", "baz", "qux")); (2)

        if (/*another condition*/) {
            headers = headers.putHeader("a", "b") (3)
        } else {
            headers = headers.putHeaders(Map.of("c", MultiValueHeader.of("d", "e"))) (4)
        }

        return new TransportMessage(headers, SerializationHelper.objectToString(toSend)); (5)
    }
}
1 Creating a MessageHeaders instance with just a single header (foo) holding a single value (bar)
2 Creating a MessageHeaders instance from a Map, each key-value pair corresponding to a header name and its value
3 Notice the assignment to headers — MessageHeaders is an immutable type so putHeader creates a new instance that contains the additional a header
4 It is also possible to create a multi-value header — just use an instance of MultiValueHeader type as a wrapper for your values
5 Finally, don’t forget to create the resulting TransportMessage with the correct instance of MessageHeaders