0

I am writing client side REST GET call using Spring RestTemplate. I need to pass http headers to the GET call.

Please find the code snippet:

String url = "http://<hostname>:7001/api?id=231";
ResponseEntity<ResponseObject> getEntity = this.restTemplate.getForEntity(url, ResponseObject.class);
return getEntity .getBody();

org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
headers.set("Accept", "application/xml");
headers.set("username", "ABC");

I need to pass above headers like Accept and username in this REST get call. What code changes are needed for the same so that i can pass headers in RestTemplate.

azaveri7
  • 793
  • 3
  • 18
  • 48

3 Answers3

1

getForEntity doesn't support setting headers. Use exchange instead:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/xml");
headers.set("username", "ABC");

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<ResponseObject> response = restTemplate.exchange(
    url, HttpMethod.GET, entity,ResponseObject.class);
Aditya Narayan Dixit
  • 2,105
  • 11
  • 23
0

Use your code as:

org.springframework.http.HttpHeaders headers = new 
org.springframework.http.HttpHeaders();
headers.set("Accept", "application/xml");
headers.set("username", "ABC");

String url = "http://<hostname>:7001/api?id=231";
ResponseEntity<ResponseObject> getEntity = 
this.restTemplate.exchange(url,HttpMethod.GET,new HttpEntity<>( headers),ResponseObject.class);
return getEntity .getBody();
Sudip Bolakhe
  • 513
  • 5
  • 16
0

Generic rest template executor method:

public <T, E extends TIBCOResponse> E executeRequest(HttpMethod method, 
        HttpHeaders httpHeaders, 
        String url,
        T requestBody,
        Map<String, String> paramters, 
        Class<E> clazz) {

    HttpEntity<T> entity = new HttpEntity<>(requestBody, httpHeaders);

    RestTemplate restTemplate = new RestTemplate();

    ResponseEntity<E> response = restTemplate.exchange(url, method, entity, clazz, paramters);

    return response.getBody();
}

Service Method Implementation:

public ResponseObject FuncCallerInsideRest(IntegrationDTO integrationDTO) {

    String OPERATION_URL = "/FindAccountInfo?accountNumber="+integrationDTO.getAccountNumber();
    Map<String, String> parameters = new HashMap<>();
    httpHeaders = new HttpHeaders();

    httpHeaders.set("RetryLimit", "2");
    httpHeaders.set("Authorization", "abcd");
    httpHeaders.set("SessionID", integrationDTO.getSessionID());

    ResponseObject ResponseObject = this.executeRequest(HttpMethod.GET, httpHeaders,
            BASE_URL.concat(PATH_URL.concat(OPERATION_URL)), null, parameters,
            ResponseObject.class);

    return ResponseObject;
}
Ali Azim
  • 160
  • 1
  • 15