Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding headers to postForObject() method of RestTemplate in spring

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?

like image 556
Sadashiv Avatar asked Sep 11 '17 15:09

Sadashiv


People also ask

How do you add a header to RestTemplate?

I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders . (You can also specify the HTTP method you want to use.) For example, RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.

What is RestTemplate postForObject?

Posting JSON With postForObject. RestTemplate's postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.

How do you call a POST method using RestTemplate in Java?

put("email", "[email protected]"); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate. postForEntity( url, params, String. class );

How do you beat bearer token in RestTemplate?

Setting bearer token for a GET request RestTemplate restTemplate = new RestTemplate(); String customerAPIUrl = "http://localhost:9080/api/customer"; HttpHeaders headers = new HttpHeaders(); headers. set("Authorization", "Bearer " + accessToken); //accessToken can be the secret key you generate. headers.


2 Answers

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); 
like image 133
Mykola Yashchenko Avatar answered Oct 16 '22 18:10

Mykola Yashchenko


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.

like image 21
Kenny Tai Huynh Avatar answered Oct 16 '22 19:10

Kenny Tai Huynh