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?
Asked
Active
Viewed 5,407 times
5
-
post your code, what headers, and how far you have gotten. – Toerktumlare Nov 22 '19 at 23:44
3 Answers
16
In case of above answer did not work for you, try below
HttpHeaders httpHeaders = HttpHeaders.writableHttpHeaders(httpEntity.getHeaders());

ExploreEv
- 725
- 8
- 8
-
1It works for me, thanks ! I noticed that the headers in the actual httpEntity are updated when httpHeaders is updated. – mistergreen Jan 14 '22 at 07:44
0
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.

Xelian
- 16,680
- 25
- 99
- 152
-1
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"));

tsarenkotxt
- 3,231
- 4
- 22
- 38
-
6This doesn't work in the latest Spring version at the time of writing this (5.2.6). The constructor simply stores a reference to the `ReadOnlyHttpHeaders` instance passed in and delegates all operations to it, which all throw an exception (because it's read only, of course). – Hasan Aslam May 28 '20 at 15:46