RestTemplate Example

This is a rest template example – how to exchange with a REST web service to get a certain type of data back.

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

public class RestTemplateExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/items";

        // Create headers
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer your_token_here");
        headers.set("Accept", "application/json");

        // Build the request entity with headers
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        // Make the exchange call
        ResponseEntity<List<ItemData>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<List<ItemData>>() {}
        );

        // Get the response headers
        HttpHeaders responseHeaders = response.getHeaders();

        // Log response headers
        responseHeaders.forEach((key, value) -> 
                System.out.println(key + ": " + String.join(", ", value))
        );

        // Get the body
        List<ItemData> items = response.getBody();

        if (items != null) {
            items.forEach(System.out::println);
        } else {
            System.out.println("No items received.");
        }
    }
}