Retrofit은 안드로이드 앱에서 서버와 쉽게 통신할 수 있는 가장 널리 사용되는 라이브러리입니다. 이번 포스트에서는 Retrofit을 활용하여 API 통신하는 방법을 기초부터 상세히 소개합니다.
1. Retrofit이란?
Retrofit은 Square에서 만든 타입 안전(type-safe)의 REST 클라이언트로, HTTP 통신을 쉽게 해주는 라이브러리입니다.
- 코드 간결화 및 가독성 향상
- 비동기 처리 지원
2. 프로젝트에 Retrofit 추가하기
build.gradle(:app)에 의존성 추가:
implementation 'com.squareup.retrofit2:retrofit:2.11.0'
implementation 'com.squareup.retrofit2:converter-gson:2.11.0'
3. Retrofit 기본 구조 이해하기
기본 API 인터페이스 정의 예시:
public interface ApiService {
@GET("users/{id}")
Call<User> getUser(@Path("id") int userId);
}
4. Retrofit을 이용한 API 요청 구현
레트로핏 객체 생성 예제:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
API 요청 및 응답 처리 예제:
apiService.getUser(1).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if(response.isSuccessful()) {
User user = response.body();
// 성공적으로 응답받은 데이터 처리
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// 오류 처리
}
});
5. Coroutine과 Retrofit을 이용한 비동기 통신 예제 (Kotlin)
Retrofit 인터페이스:
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") userId: Int): User
}
Coroutine으로 비동기 호출 예제:
CoroutineScope(Dispatchers.IO).launch {
try {
val user = apiService.getUser(1)
withContext(Dispatchers.Main) {
// UI 업데이트
}
} catch (e: Exception) {
// 에러 처리
}
}
6. 에러 처리 및 예외 상황 관리하기
- HTTP 상태 코드 별로 처리 방안 구분
- 네트워크 상태 변화 대응 방법 구현
- 사용자에게 명확한 피드백 제공 방법 정리
이 가이드를 따라 Retrofit을 이용해 효율적인 API 통신 기능을 구현할 수 있습니다.