Search code examples
springweb-servicesrestwebservice-clientresttemplate

How to pass header Information as key value pair to consume rest service using spring


I got a url of web service which returns values in json format but it needs header information in get request as key value pair e.g. I need to pass Emp_code as key and 'xyz' as value to get details of all employees in postman.

private static void getEmployees()

{ final String uri = "http://abc/springrestexample/employees";

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);

System.out.println(result);

}

In above code how can I pass header info(key-value) so as to consume service.


Solution

  • You can add headers to your request by using the following example:

    org.springframework.http.HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add("yourHeaderKey", "yourHeadeerValue");
    org.springframework.http.HttpEntity<?> httpEntity = new HttpEntity<>(requestHeaders);
    

    And then issuing this call to your restTemplate:

        restTemplate.exchange(uri, org.springframework.http.HttpMethod.GET, httpEntity , String.class);