简体   繁体   English

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

[英]How to set header while creating Spring's RestTemplate?

We can set a header to rest template while firing the call ie restTemplate.exchange(postUrl, HttpMethod.GET, entity, String.class); 我们可以在触发调用时设置一个标头来休息模板,即restTemplate.exchange(postUrl, HttpMethod.GET, entity, String.class);
where entity contains headers. 其中实体包含标题。

But for my requirement I want to set cookie header while creating the restTemplate itself and not while firing the actual call. 但是对于我的要求,我想在创建restTemplate本身时设置cookie头,而不是在触发实际调用时。 I don't want to repeat the code of creating HttpEntity and setting headers to it. 我不想重复创建HttpEntity并为其设置标头的代码。

Is there a way to set headers while creating restTemplate? 有没有办法在创建restTemplate时设置标题?

Looks like you can inject your own HttpMessageConverter implementation which accepts all requests - canWrite returns true . 看起来你可以注入你自己的接受所有请求的HttpMessageConverter实现 - canWrite返回true And add desired headers within write method to the HttpOutputMessage.getHeaders() . 并在write方法中将所需的头添加到HttpOutputMessage.getHeaders()

I remember as I overrided once ClientHttpRequestFactory.createRequest to do something similar for other server-specific static header. 我记得,当ClientHttpRequestFactory.createRequest为其他特定于服务器的静态标头执行类似操作时,我会重写。

UPDATE UPDATE

From the code of RestTemplate.doWithRequest you can see if there is no request.body then it reads headers from the request entity . RestTemplate.doWithRequest的代码中,您可以看到是否没有request.body然后它从request entity读取headers

In that case you can simply extend RestTemplate and return from the overridden httpEntityCallback your own RequestCallback . 在这种情况下,你可以简单地扩展RestTemplate从覆盖返回httpEntityCallback自己RequestCallback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM