Adding headers to postForObject() method of RestTemplate in spring

Sadashiv picture Sadashiv · Sep 11, 2017 · Viewed 43.3k times · Source

I am calling web service using below method.

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?

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

How to add headers in this case?

Answer

Mykola Yashchenko picture Mykola Yashchenko · Sep 11, 2017

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);