Android 공부/네트워크 통신
Retrofit
posite
2026. 2. 21. 15:29
Retrofit
- 안드로이드와 서버간의 REST API 통신을 도와주는 라이브러리로, OkHTTP에 기반을 두고 있으며 현재 가장 널리 쓰이는 통신 라이브러리이다.
- Annotation으로 HTTP 메소드를 정의함으로서 코드의 구현이 쉬워지며 개발자들은 행위를 손쉽게 알아볼 수 있게 되어 직관적으로 코드를 설계할 수 있게 된다.
- JSON, XML을 자동을 파싱해주는 Converter 연동을 지원해주기 때문에, 개발자 입장에서는 유지보수가 매우 편리하다.
- AndroidMenifest.xml에서 인터넷 permission 설정 및 http 사용가능하게 설정해야한다.
<uses-permission android:name="android.permission.INTERNET" /> - JSON 데이터 구조에 맞는 모델 클래스를 선언해야 한다. DTO 클래스의 역할을 한다 이 모델 클래스 또한 Android Studio에서 plugin으로 편하게 만들 수 있다.
import android.os.Parcelable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlinx.parcelize.Parcelize @Parcelize @JsonClass(generateAdapter = true) data class CategoryDto( @field:Json(name = "strCategory") val strCategory: String, @field:Json(name = "strCategoryThumb") val strCategoryThumb: String, @field:Json(name = "strCategoryDescription") val strCategoryDescription: String ) : Parcelable - 서비스 인터페이스를 정의해야 한다. annotation 으로 HTTP Method 를 지정하고, 서버에 전송할 데이터를 추가하면 Call 객체를 자동으로 생성하는 구조이다 annotation으로 body와 query, field등도 설정할 수 있다
import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface MealService { @GET("categories.php") suspend fun getCategories(): Response<CategoryResponse> @GET("filter.php") suspend fun getMealsByCategory(@Query("c") category: String): Response<MealResopnse> } - Retrofit 객체를 생성해야 한다 baseUrl을 설정해주고 Gson 혹은 Moshi를 통해 Converter를 등록하며 추가로 읽기, 쓰기 timeout등을 설정하고싶다면 okhttpClient 객체를 만들어 설정 한 후 Retrofit객체를 Builder로 build 할 때 .client()에 넣어주면 된다
private val moshi : Moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() private val okHttpClient = OkHttpClient.Builder() .connectTimeout(5, TimeUnit.MINUTES) .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .retryOnConnectionFailure(false) .build() private val retrofit = Retrofit.Builder().baseUrl(BuildConfig.api) .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() private var api = retrofit.create(MealService::class.java)