在 spring 中向 RestTemplate 的 postForObject() 方法添加标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46159097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:30:23  来源:igfitidea点击:

Adding headers to postForObject() method of RestTemplate in spring

springrestweb-servicesrestful-authentication

提问by Sadashiv

I am calling web service using below method.

我正在使用以下方法调用 Web 服务。

ResponseBean responseBean = getRestTemplate()
    .postForObject(url, customerBean, ResponseBean.class);

Now my requirement got changed. I want to send 2 headers with the request. How should I do it?

现在我的要求改变了。我想随请求发送 2 个标头。我该怎么做?

Customer bean is a class where which contain all the data which will be used as request body.

客户 bean 是一个类,其中包含将用作请求正文的所有数据。

How to add headers in this case?

在这种情况下如何添加标题?

回答by Mykola Yashchenko

You can use HttpEntity<T>for your purpose. For example:

您可以HttpEntity<T>根据自己的目的使用。例如:

CustomerBean customerBean = new CustomerBean();
// ...

HttpHeaders headers = new HttpHeaders();
headers.set("headername", "headervalue");      

HttpEntity<CustomerBean> request = new HttpEntity<>(customerBean, headers);

ResponseBean response = restTemplate.postForObject(url, request, ResponseBean.class); 

回答by Kenny Tai Huynh

Just use the org.springframework.http.HttpHeadersto create your headers and add CustomBean. Sth looks like:

只需使用org.springframework.http.HttpHeaders来创建您的标头并添加 CustomBean。看起来像:

 CustomerBean customerBean = new CustomerBean();
 HttpHeaders headers = new HttpHeaders();

// can set the content Type
headers.setContentType(MediaType.APPLICATION_JSON);

//Can add token for the authorization
headers.add(HttpHeaders.AUTHORIZATION, "Token");

headers.add("headerINfo", "data");

//put your customBean to header
HttpEntity< CustomerBean > entity = new HttpEntity<>(customBean, headers);
//can post and get the ResponseBean 
restTemplate.postForObject(url, entity, ResponseBean.class);
//Or return the ResponseEntity<T>  

Hope this help.

希望这有帮助。