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?
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.
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.
put("email", "[email protected]"); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate. postForEntity( url, params, String. class );
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With