RestTemplate.exchange() is the most flexible method in RestTemplate for making HTTP requests. It provides full control over the request and response.
Method Signature:
public <T> ResponseEntity<T> exchange(String url, // The URL to callHttpMethod method, // HTTP method (GET, POST, PUT, DELETE, etc.)HttpEntity<?> requestEntity, // Request body and headers (can be null)ParameterizedTypeReference<T> responseType // Expected response type
)
In the Code:
ResponseEntity<Map<String,String>> result = new RestTemplate().exchange("https://dog.ceo/api/breeds/image/random", // URLHttpMethod.GET, // HTTP methodnull, // No request body/headersreference // Response type reference
);
Parameters Breakdown:
-
- URL: "https://dog.ceo/api/breeds/image/random"
The endpoint to call
- URL: "https://dog.ceo/api/breeds/image/random"
-
- HttpMethod: HttpMethod.GET
HTTP verb: GET, POST, PUT, DELETE, PATCH, etc.
- HttpMethod: HttpMethod.GET
-
- HttpEntity: null
Contains request body and headers
null means no body or custom headers
- HttpEntity: null
-
- ParameterizedTypeReference: reference
Preserves generic type information for Map<String,String>
- ParameterizedTypeReference: reference
Return Value:
ResponseEntity
- Status code: result.getStatusCode()
- Headers: result.getHeaders()
- Body: result.getBody()
Alternative Approaches:
With headers:
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer token");
HttpEntity<Void> entity = new HttpEntity<>(headers);ResponseEntity<Map<String,String>> result = restTemplate.exchange(url, HttpMethod.GET, entity, reference
);
With request body (POST):
HttpEntity<ReleaseNote> entity = new HttpEntity<>(releaseNote);ResponseEntity<ReleaseNote> result = restTemplate.exchange(url, HttpMethod.POST, entity, ReleaseNote.class
);
Why Use exchange() vs Other Methods:
- Full control: Access to status codes, headers, and body
- Generic support: Works with complex types via ParameterizedTypeReference
- Flexibility: Handles any HTTP method
- Error handling: Better control over HTTP status codes
The code uses it for a health check - making a GET request and examining both status code and response body.