FGreg
FGreg

Reputation: 15330

How to keep only some message headers and remove all others?

How do I keep only specific headers but get rid of all other headers?

I'm trying to remove irrelevant headers that were set by an upstream HttpRequestHandlingMessagingGateway.

I tried specifying a handle() function that returns a new message containing only the headers I'm interested in but it does not seem to work. The log message contains a bunch of HTTP headers that were set from the upstream HttpRequestHandlingMessagingGateway.

IntegrationFlows.from(myChannel())
                // Strip off the HTTP specific headers
                .handle((payload, headers) -> MessageBuilder
                        .withPayload(payload)
                        .setHeader("myCustomHeader1", headers.get("myCustomHeader1", String.class))
                        .setHeader("myCustomHeader2", headers.get("myCustomHeader2", String.class))
                        .build()
                )
                .log()

I see there is a HeaderFilter but it requires you to know the name of the headers you want to remove. In my case I only want to keep 2 custom headers and remove everything else.

Upvotes: 0

Views: 1350

Answers (2)

FGreg
FGreg

Reputation: 15330

Artem Bilan's comment pointed me in the right direction for how I would do it inline. I just could not get the syntax correct previously, here's how it looks with an inline transform():

IntegrationFlows.from(myChannel())
                // Strip off the HTTP specific headers
                .transform(Message.class, message -> MessageBuilder
                            .withPayload(message.getPayload())
                            .setHeader("myCustomHeader1", message.getHeaders().get("myCustomHeader1", String.class))
                            .setHeader("myCustomHeader2", message.getHeaders().get("myCustomHeader2", String.class))
                            .build()
                )
                .log()

Upvotes: 1

Gary Russell
Gary Russell

Reputation: 174799

class HeaderStripper {

    public Message<?> strip(Message<?> msg) {
        return org.springframework.integration.support.MessageBuilder.withPayload(msg.getPayload())
                .setHeader("foo", msg.getHeaders().get("foo"))
                .setHeader("bar", msg.getHeaders().get("bar"))
                .build();
    }

}

and then

.transform(new HeaderStripper())

Upvotes: 3

Related Questions