SeouliteLab

[Java/자바] Spring RestTemplate을 활용한 웹 서비스 통신 본문

프로그래밍

[Java/자바] Spring RestTemplate을 활용한 웹 서비스 통신

Seoulite Lab 2024. 3. 14. 14:08

Spring RestTemplate은 Spring 프레임워크에서 제공하는 HTTP 클라이언트 라이브러리로, 간편하게 RESTful 웹 서비스와 통신할 수 있습니다. 이를 통해 다양한 형태의 HTTP 요청을 보내고, 응답을 받아올 수 있습니다. 이번 포스트에서는 RestTemplate을 사용한 여러 예제를 살펴보겠습니다.

1. 기본 GET 요청

먼저 간단한 GET 요청을 보내보겠습니다. RestTemplate을 사용하여 서버로부터 JSON 형태의 응답을 받아와서 출력하는 예제입니다.

Example 1: Basic GET Request

import org.springframework.web.client.RestTemplate;

public class BasicGetExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/data";
        String response = restTemplate.getForObject(url, String.class);
        System.out.println("Response: " + response);  // 출력 결과: 서버 응답 데이터
    }
}

2. Path Variable을 이용한 GET 요청

PathVariable을 이용하여 동적인 URL을 생성하여 GET 요청을 보내는 예제입니다.

Example 2: GET Request with Path Variable

import org.springframework.web.client.RestTemplate;

public class PathVariableExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/data/{id}";
        String response = restTemplate.getForObject(url, String.class, 123);
        System.out.println("Response: " + response);  // 출력 결과: 서버 응답 데이터
    }
}

3. POST 요청

RestTemplate을 사용하여 POST 요청을 보내고, 서버로부터 응답을 받아오는 예제입니다.

Example 3: POST Request

import org.springframework.web.client.RestTemplate;

public class PostRequestExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/data";
        String requestBody = "{\"key\": \"value\"}";
        String response = restTemplate.postForObject(url, requestBody, String.class);
        System.out.println("Response: " + response);  // 출력 결과: 서버 응답 데이터
    }
}

4. RESTful API에 데이터 전송

RestTemplate을 사용하여 RESTful API에 데이터를 전송하는 예제입니다.

Example 4: Sending Data to RESTful API

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class SendDataExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/data";
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        String requestBody = "{\"key\": \"value\"}";
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        
        String response = restTemplate.postForObject(url, requestEntity, String.class);
        System.out.println("Response: " + response);  // 출력 결과: 서버 응답 데이터
    }
}

5. 응답 해석 및 처리

RestTemplate으로 받은 응답 데이터를 해석하고 처리하는 예제입니다.

Example 5: Parsing and Processing Response

import org.springframework.web.client.RestTemplate;

public class ProcessResponseExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/data";
        String response = restTemplate.getForObject(url, String.class);
        
        // 응답 데이터 처리 로직 작성
        // 예: JSON 파싱, 객체 매핑 등
        
        System.out.println("Response: " + response);  // 출력 결과: 서버 응답 데이터
    }
}

6. 오류 처리

RestTemplate 사용 시 발생할 수 있는 오류를 처리하는 방법에 대한 예제입니다.

Example 6: Error Handling

import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class ErrorHandlingExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/data";
        
        try {
            String response = restTemplate.getForObject(url, String.class);
            System.out.println("Response: " + response);  // 출력 결과: 서버 응답 데이터
        } catch (RestClientException e) {
            System.err.println("Error: " + e.getMessage());  // 출력 결과: 오류 메시지
        }
    }
}

위 예제들을 통해 Spring RestTemplate을 활용하여 간편하게 웹 서비스와 통신하는 방법을 알아보았습니다.