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

时间:2017-09-11 15:19:41

标签: spring rest web-services restful-authentication

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

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

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

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

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

2 个答案:

答案 0 :(得分:28)

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

答案 1 :(得分:5)

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

希望得到这个帮助。