blog

Retrofit 사용

Retrofit은 개발자가 간단한 어노테이션으로 HTTP 요청을 정의할 수 있는 유형 안전 HTTP 클라이언트입니다. Square에서 개발했으며 안드로이드 및 자바 애플리케이션에서...

Oct 11, 2025 · 3 min. read
シェア

간단한 소개

Retrofit은 개발자가 간단한 어노테이션으로 HTTP 요청을 정의할 수 있는 타입 안전 HTTP 클라이언트입니다. Square에서 개발했으며 Android 및 Java 애플리케이션에서 매우 인기가 있습니다. 주요 기능은 다음과 같습니다:

  1. 유형 안전 요청: Retrofit은 인터페이스와 어노테이션을 사용하여 API 엔드포인트를 정의합니다. URL, 요청 메서드, 쿼리 매개변수 등을 정의할 수 있습니다.

  2. 유연한 데이터 구문 분석: Retrofit은 Gson, Jackson, Moshi 등 다양한 데이터 구문 분석기를 지원하므로 JSON 또는 기타 형식의 응답 데이터를 Java 객체로 쉽게 변환할 수 있습니다.

  3. 손쉬운 통합: 다른 라이브러리와 잘 연동되어 네트워크 연결, 캐싱 등을 제공합니다.

  4. 비동기 및 동기식 접근 방식: Retrofit은 동기식 및 비동기식 API 호출을 모두 지원하므로 필요에 따라 호출을 차단하거나 콜백을 사용하도록 선택할 수 있습니다.

  5. 다양한 용도: Retrofit은 Android 개발에서 매우 인기가 있지만, 네트워크 요청 처리를 간소화하기 위해 모든 Java 애플리케이션에서도 사용할 수 있습니다.

실제 사용 사례

SpringBoot에서 Retrofit을 사용하려면 몇 가지 기본 설정이 필요합니다. 다음은 SpringBoot 애플리케이션에서 Retrofit을 통합하고 사용하는 방법을 보여주는 간단한 예제입니다.

먼저 pom.xml 또는 build.gradle 파일에 Retrofit 종속성을 추가합니다. Maven을 예로 들어보겠습니다:

<dependencies>
 <!-- Retrofit dependencies -->
 <dependency>
 <groupId>com.squareup.retrofit2</groupId>
 <artifactId>retrofit</artifactId>
 <version>2.9.0</version>
 </dependency>
 <dependency>
 <groupId>com.squareup.retrofit2</groupId>
 <artifactId>converter-gson</artifactId>
 <version>2.9.0</version>
 </dependency>
</dependencies>

그런 다음 HTTP 요청을 정의하기 위한 인터페이스를 만듭니다. 간단한 JSON 플레이스홀더 API가 있다고 가정해 보겠습니다:

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface JsonPlaceholderApi {
 @GET("/posts/{id}")
 Call<Post> getPost(@Path("id") int postId);
}

여기에 JSON 응답을 매핑하는 간단한 Java 클래스를 게시합니다:

public class Post {
 private int id;
 private int userId;
 private String title;
 private String body;
 // 게터 및 세터 메서드 생략
}

그런 다음 구성 클래스를 생성하여 Retrofit을 구성합니다:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
@Configuration
public class RetrofitConfiguration {
 @Bean
 public Retrofit retrofit() {
 return new Retrofit.Builder()
 .baseUrl("https://..com")
 .addConverterFactory(GsonConverterFactory.create())
 .build();
 }
 @Bean
 public JsonPlaceholderApi jsonPlaceholderApi(Retrofit retrofit) {
 return retrofit.create(JsonPlaceholderApi.class);
 }
}

마지막으로 서비스 또는 컨트롤러에 JsonPlaceholderApi를 삽입하여 사용할 수 있습니다:

import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Response;
import java.io.IOException;
@Service
public class MyService {
 private final JsonPlaceholderApi jsonPlaceholderApi;
 public MyService(JsonPlaceholderApi jsonPlaceholderApi) {
 this.jsonPlaceholderApi = jsonPlaceholderApi;
 }
 public Post getPost(int postId) throws IOException {
 Call<Post> call = jsonPlaceholderApi.getPost(postId);
 Response<Post> response = call.execute();
 if (response.isSuccessful()) {
 return response.body();
 } else {
 // 오류 조건 처리
 throw new RuntimeException("Failed to fetch post");
 }
 }
}

이 예제에서 MyService 클래스는 JsonPlaceholderApi를 사용하여 동기식 HTTP 요청을 수행합니다. 비동기 메서드를 사용하여 요청을 처리할 수도 있습니다. 이는 기본적인 예시일 뿐이며 실제 애플리케이션에는 더 복잡한 오류 처리 및 구성이 필요할 수 있습니다.

전반적으로 Retrofit은 효율적이고 강력하며 사용하기 쉬운 네트워킹 라이브러리로, 안드로이드 및 자바 애플리케이션에서 HTTP 요청을 처리하는 데 적합합니다.

Read next

백 스택이 플랫폼 엔지니어링의 새로운 트렌드가 될까요?

백 스택이란?\n\n\n\nBackstage는 개발자 포털을 구축하기 위한 오픈 플랫폼입니다. 중앙 집중식 소프트웨어 카탈로그를 기반으로 하는 백스테이지를 통해 인프라의 질서를 회복하고 제품 팀이 고품질 코드를 신속하게 제공할 수 있습니다!

Oct 11, 2025 · 2 min read