java - 如何在创建 Spring 的 RestTemplate 时设置标题?

标签 java spring resttemplate

我们可以在触发调用时为 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 no request.body then it reads headers from the request entity.

在这种情况下,您可以简单地扩展 RestTemplate 并从重写的 httpEntityCallback 返回您自己的 RequestCallback

关于java - 如何在创建 Spring 的 RestTemplate 时设置标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026073/

相关文章:

json - Spring rest 模板无法从 text/html 转换

rest - restTemplate.exchange()方法有什么作用?

java - 从数组列表中提取组合字符串

java - 为 Java LocalDateTime 生成正确的 swagger 规范

java - 如何调整物体在 2D 运动场上移动的速度?

Java 泛型 : Type mismatch: cannot convert from Integer to K

java - Spring Oauth2 重定向 uri 没有改变

java - Spring Boot 与 Apache Shiro

java - Spring、JPA 和 Hibernate - 如何在没有并发问题的情况下增加计数器

java - Spring 启动 : no String-argument constructor/factory method to deserialize from String value