Android

[Android] Retrofit2 사용하여 API 통신하기

이예짜니 2021. 8. 3. 23:46

Retrofit 이란,

대표적인 REST API 통신 라이브러리입니다.

OkHttp를 네트워크 계층으로 활용하고 그 위에 구축되었습니다.

HttpUrlConection과 OkHttp의 반복 작업을 대신 해주어 간편하게 사용할 수 있습니다.

컨버터를 이용한 객체 매핑과 코루틴을 지원합니다.

API 구현 시 Tip,

1. Postman을 사용하여 미리 API에 대한 테스트 및 응답결과를 확인할 수 있다.

2. 안드로이드 스튜디오에서 플러그인 Json to Kotlin Class을 사용하여 Json타입의 응답결과를 입력하면 DTO Class를 자동으로 생성해준다.

사용방법,

테스트를 위해 Github API를 사용했으며, Kotlin으로 작성하였고 비동기 처리는 Coroutines을 사용했습니다.

라이브러리 추가

build.gradle(:app)

dependencies {
	// Retrofit 버전 (공식문서에 따라 최신버전으로 사용)
	def retrofit_ver = '2.9.0'
	// Retrofit 라이브러리
	implementation "com.squareup.retrofit2:retrofit:$retrofit_ver"
	// Json 타입의 응답을 DTO에 매핑시켜주기 위한 컨버터
	implementation "com.squareup.retrofit2:converter-gson:$retrofit_ver"
}

인터넷 권한 추가

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="...">
		// 네트워크 통신을 위한 권한
    <uses-permission android:name="android.permission.INTERNET" />

</manifest>

DTO Class 생성

API 요청 후 응답결과에 대해 매핑할 클래스

아래 예시는 https://api.github.com/users/Yeechaan 요청 후 Json타입의 결과(간소화)이다.

{
  "login": "Yeechaan",
  "blog": "https://dev-traveller-chan.tistory.com/",
  "location": "Seoul",
}

해당 Json의 결과에 대해 data class로 생성하면 아래와 같고, @SerializedName을 통해 Json의 키값과 변수를 매핑시켜준다. (키값과 변수명이 같다면 해당 어노테이션 생략 가능)

import com.google.gson.annotations.SerializedName

data class GitUserDTO(
    @SerializedName("login")
    val login: String,
    @SerializedName("blog")
    val blog: String,
    @SerializedName("location")
    val location: String,
)

Interface 정의

HTTP API를 인터페이스 형태로 사용한다.

@GET을 통해 Http Method 정의하고, getUserInfo() 호출 시 login 파라미터(사용자의 Git ID)를 전달받아 EndPoint를 정의한다.

import retrofit2.http.GET
import retrofit2.http.Path

interface GitApiService {
    @GET("users/{login}")
    suspend fun getUserInfo(
        @Path("login") login: String
    ): GitUserDTO
}

Retrofit.Builder 생성

val retrofit: Retrofit = Retrofit.Builder()
    .baseUrl("https://api.github.com/users/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val service: GitApiService = retrofit.create(GitApiService::class.java)

Retrofit 클래스로 baseUrl지정하고, 응답결과를 파씽하기 위한 컨버터 정의 후 GitApiService 인터페이스를 구현하여 생성합니다.

API 요청하기

val response = service.getUserInfo("Yeechaan")

응답결과


참고

http://devflow.github.io/retrofit-kr/