添加 headers 到 spring 中 RestTemplate 的 postForObject() 方法

Adding headers to postForObject() method of RestTemplate in spring

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

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

现在我的要求变了。我想随请求发送 2 headers。 我应该怎么做?

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

这种情况下如何添加headers?

您可以根据自己的目的使用 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); 

只需使用 org.springframework.http.HttpHeaders 创建您的 headers 并添加 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>  

希望对您有所帮助。