With AI

Spring 환경에서 API 호출하기

  • -
반응형

 

✅ 1. RestTemplate (Spring Boot 2.4 이하 권장)

RestTemplate은 간단한 HTTP 요청을 처리할 수 있는 클래스로, exchange(), getForObject(), postForEntity() 등을 제공함.
Spring Boot 2.4 이상에서는 사용이 비권장(deprecated)되었으며, WebClient 사용이 권장됨.

📝 예제 코드 (GET 요청)

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        System.out.println(response.getBody());
    }
}

📝 POST 요청 예제

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

import java.util.HashMap;
import java.util.Map;

public class RestTemplatePostExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://jsonplaceholder.typicode.com/posts";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("title", "foo");
        requestBody.put("body", "bar");
        requestBody.put("userId", 1);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        System.out.println(response.getBody());
    }
}

 

✅ 2. WebClient (Spring Boot 2.4 이상 권장)

비동기 처리를 지원하며, RestTemplate의 대체재로 Spring 5부터 제공됨.

📝 예제 코드 (GET 요청)

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

public class WebClientExample {
    public static void main(String[] args) {
        WebClient webClient = WebClient.create("https://jsonplaceholder.typicode.com");

        Mono<String> response = webClient.get()
                .uri("/posts/1")
                .retrieve()
                .bodyToMono(String.class);

        System.out.println(response.block()); // 동기 호출
    }
}

📝 POST 요청 예제

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

public class WebClientPostExample {
    public static void main(String[] args) {
        WebClient webClient = WebClient.builder()
                .baseUrl("https://jsonplaceholder.typicode.com")
                .build();

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("title", "foo");
        requestBody.put("body", "bar");
        requestBody.put("userId", 1);

        Mono<String> response = webClient.post()
                .uri("/posts")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class);

        System.out.println(response.block()); // 동기 호출
    }
}

WebClient는 기본적으로 비동기 처리를 하지만, .block()을 사용하면 동기적으로 변환 가능.
✔ retrieve()를 사용하면 간편하게 응답을 받을 수 있음.
✔ exchangeToMono()를 활용하면 커스텀 에러 핸들링 가능.

 

✅ 3. FeignClient (Spring Cloud OpenFeign)

Spring Cloud에서 제공하는 선언형 HTTP 클라이언트로, 인터페이스 기반으로 API를 호출할 수 있음.
Feign을 사용하면 API 호출을 인터페이스 선언만으로 쉽게 처리 가능

📌 Feign 설정 (의존성 추가)

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

📝 FeignClient 사용 예제

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "postClient", url = "https://jsonplaceholder.typicode.com")
public interface PostClient {
    @GetMapping("/posts/{id}")
    String getPost(@PathVariable("id") int id);
}

📝 FeignClient 사용 방법

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PostController {

    @Autowired
    private PostClient postClient;

    @GetMapping("/fetchPost")
    public String fetchPost(@RequestParam int id) {
        return postClient.getPost(id);
    }
}

✔ 인터페이스만 선언하면 Spring이 자동으로 구현체를 만들어 줌
✔ RestTemplate이나 WebClient보다 간결함
✔ Spring Boot와 통합이 쉬움

 

✅ 4. Apache HttpClient (Low-Level HTTP Client)

Apache의 저수준 HTTP 클라이언트 라이브러리.
대규모 트래픽을 처리할 때 커넥션 풀링을 활용 가능
✔ RestTemplate 내부적으로 사용됨

📌 의존성 추가

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

📝 Apache HttpClient 예제

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ApacheHttpClientExample {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
        }
    }
}

가장 저수준의 HTTP 호출 방식
✔ 커넥션 풀링 및 세부적인 설정이 가능하지만 코드가 복잡함
✔ 일반적인 사용에서는 WebClient나 FeignClient가 더 적합

 

✅ 5. OkHttp (Square 라이브러리)

가볍고 빠른 HTTP 클라이언트.
✔ REST API 호출 시 성능이 뛰어나며, Android에서도 많이 사용됨.

📌 의존성 추가

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
</dependency>

📝 OkHttp 예제

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpExample {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}

✔ Apache HttpClient보다 가볍고 빠름
✔ 비동기 API도 제공


결론: 언제 어떤 방법을 선택해야 할까?

사용 방법 장점 추천 사용
RestTemplate 간단한 HTTP 요청 Spring Boot 2.4 이하에서 사용
WebClient 비동기, 성능 최적화 Spring Boot 2.4 이상
FeignClient 선언형 API 호출 마이크로서비스, Spring Cloud
Apache HttpClient 저수준 HTTP 제어 커넥션 풀 최적화 필요 시
OkHttp 경량 & 성능 최적화 고성능 API 호출, Android

Spring Boot 2.4 이상에서는 WebClient 사용 추천
마이크로서비스 환경에서는 FeignClient 사용 추천
성능 최적화가 필요하면 Apache HttpClient or OkHttp 고려

반응형

'With AI' 카테고리의 다른 글

Authorization 헤더에서 Bearer를 붙이는 이유  (0) 2025.03.07
Spring Boot의 애플리케이션 설정파일  (0) 2025.03.07
Vue.js란?  (0) 2025.03.04
Dart란?  (0) 2025.03.03
RESTful이란?  (1) 2025.02.28
Contents

포스팅 주소를 복사했습니다.

이 글이 도움이 되었다면 공감 부탁드립니다.