5

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?

Jumpman
  • 145
  • 1
  • 2
  • 11

3 Answers3

16

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

HttpHeaders httpHeaders = HttpHeaders.writableHttpHeaders(httpEntity.getHeaders());
ExploreEv
  • 725
  • 8
  • 8
  • 1
    It 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
  • 6
    This 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