我们可以在触发调用时为 rest 模板设置 header ,即 restTemplate.exchange(postUrl, HttpMethod.GET, entity, String.class);
其中实体包含标题。
但根据我的要求,我想在创建 restTemplate 本身时设置 cookie header ,而不是在触发实际调用时设置。我不想重复创建 HttpEntity 并为其设置 header 的代码。
有没有办法在创建 restTemplate 时设置标题?
最佳答案
看起来您可以注入(inject)自己的 HttpMessageConverter
实现,它接受所有请求 - canWrite
返回 true
。并在 write
方法中将所需的 header 添加到 HttpOutputMessage.getHeaders()
。
我记得我重写了一次 ClientHttpRequestFactory.createRequest
以对其他特定于服务器的静态 header 执行类似的操作。
更新
From the code of
RestTemplate.doWithRequest
you can see if there is norequest.body
then it readsheaders
from therequest entity
.
在这种情况下,您可以简单地扩展 RestTemplate
并从重写的 httpEntityCallback
返回您自己的 RequestCallback
。
关于java - 如何在创建 Spring 的 RestTemplate 时设置标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026073/