在 Spring 中向 RestTemplate 的 postForObject() 方法添加标头

Posted

技术标签:

【中文标题】在 Spring 中向 RestTemplate 的 postForObject() 方法添加标头【英文标题】:Adding headers to postForObject() method of RestTemplate in spring 【发布时间】:2018-02-19 21:30:03 【问题描述】:

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

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

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

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

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

【问题讨论】:

【参考方案1】:

您可以将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); 

【讨论】:

【参考方案2】:

只需使用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>  

希望对您有所帮助。

【讨论】:

以上是关于在 Spring 中向 RestTemplate 的 postForObject() 方法添加标头的主要内容,如果未能解决你的问题,请参考以下文章

Spring的RestTemplate

为啥 Spring RestTemplate 在 Spring 中默认不是 Bean?

Spring RestTemplate 之get请求

一起学 Spring 之 RestTemplate

如何在 Spring RestTemplate 中记录响应?

Spring Cloud - 在 RestTemplate 中重试工作?