Adding headers to postForObject() method of RestTemplate in spring
You can use HttpEntity<T>
for your purpose. For example:
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);
Just use the org.springframework.http.HttpHeaders
to create your headers and add CustomBean. Sth looks like:
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.