Jumpman
Jumpman

Reputation: 165

How do I modify a response's ReadOnlyHttpHeaders in Spring?

RestTemplate.exchange is returning a ResponseEntity with ReadOnlyHttpHeaders. I want to add/modify these headers but since it is read only how do I do that?

Upvotes: 7

Views: 8775

Answers (4)

Artem Yemelin
Artem Yemelin

Reputation: 66

Make writeable header instance and use it:

HttpHeaders writableHeaders = HttpHeaders.writableHttpHeaders(headers);
writableHeaders.put(authHeader, List.of(OBFUSCATED_VALUE));

Upvotes: 0

Xelian
Xelian

Reputation: 17228

ServerHttpRequest request = exchange.getRequest().mutate().header("key", new String[] {"value"}).build();

ServerWebExchange mutatedExchange = exchange.mutate().request(request).build();

And the mutatedExchange will have a header with the new key: value pair.

Upvotes: 1

ExploreEv
ExploreEv

Reputation: 895

In case of above answer did not work for you, try below

HttpHeaders httpHeaders = HttpHeaders.writableHttpHeaders(httpEntity.getHeaders());

Upvotes: 20

tsarenkotxt
tsarenkotxt

Reputation: 3499

HttpHeaders implements MultiValueMap, you can create a new mutable HttpHeaders including ReadOnlyHttpHeaders and modify:

        HttpHeaders readOnlyHttpHeaders = ...

        HttpHeaders mutableHttpHeaders = new HttpHeaders(readOnlyHttpHeaders);
        mutableHttpHeaders.put("foo", List.of("bar"));

Upvotes: -1

Related Questions