Search code examples
springspring-bootswaggerresttemplate

How to pass header values using RestTemplate?


I am new to Spring. A project of mine needs to call an Autotask API which takes Api integration code, username and secret (password) in the headers. How do I integrate that into the Rest Template?

Below is a screenshot of the API that I am testing on swagger. Screenshot of API Call using Swagger


Solution

  • The additional parameters you need to send are all headers. You can set the headers as follows:

    HttpHeaders headers = new HttpHeaders();
    headers.set("ApiIntegrationCode", "HUCXSL...");
    headers.set("UserName", "fdfsk...");
    headers.set("Secret", "yR*42...");
    

    Then you add the headers to a new HttpEntity instance and perform the request using RestTemplate:

    HttpEntity entity = new HttpEntity(headers);
    
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    

    A very similar question has been asked here: HTTP get with headers using RestTemplate.