Ktor 탐색: Kotlin을 위한 현대적인 네트워킹 프레임워크
Source: Dev.to
Ktor는 JetBrains에서 개발한 비동기 네트워킹 프레임워크로, Kotlin으로 서버와 클라이언트 애플리케이션을 모두 구축할 수 있도록 설계되었습니다. Android 네트워킹에서 오랫동안 표준으로 자리 잡아 온 Retrofit과 달리, 많은 개발자들은 Ktor를 Kotlin‑first 네트워킹의 미래로 보고 있습니다.
Ktor와 Retrofit 중 어느 것을 선택할지는 궁극적으로 프로젝트 요구사항, 범위 및 개발자 선호도에 따라 달라집니다. 아래는 Android 프로젝트에서 Ktor를 설정하고 사용하는 실용적인 가이드입니다.
프로젝트 설정 및 종속성
Ktor 및 직렬화 플러그인 추가
루트 build.gradle.kts 파일에 Kotlin Serialization 플러그인을 적용합니다:
plugins {
id("org.jetbrains.kotlin.plugin.serialization") version "2.1.20"
}
Ktor 종속성 추가
앱‑레벨 build.gradle.kts에 필요한 Ktor 라이브러리를 포함합니다:
plugins {
id("kotlinx-serialization")
}
dependencies {
implementation(platform("io.ktor:ktor-bom:3.1.2"))
implementation("io.ktor:ktor-client-android")
implementation("io.ktor:ktor-client-serialization")
implementation("io.ktor:ktor-client-logging")
implementation("io.ktor:ktor-client-content-negotiation")
implementation("io.ktor:ktor-serialization-kotlinx-json")
}
재사용 가능한 HttpClient 만들기
재사용 가능한 클라이언트의 장점
- Persistent Connections – 연결을 유지하여 이후 요청의 지연 시간을 줄입니다.
- Kotlin Multiplatform Compatibility – Android, iOS 및 기타 타깃에서 네트워킹 로직을 공유합니다.
- Resource Management – 정리 작업(예:
client.close())을 단순화하고 누수를 방지합니다.
클라이언트 인스턴스 생성 예시
private const val NETWORK_TIME_OUT = 15_000
val httpClient = HttpClient(Android) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
install(HttpTimeout) {
requestTimeoutMillis = NETWORK_TIME_OUT
connectTimeoutMillis = NETWORK_TIME_OUT
socketTimeoutMillis = NETWORK_TIME_OUT
}
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
Log.v("KtorLogger", message)
}
}
level = LogLevel.ALL
}
install(DefaultRequest) {
header(HttpHeaders.ContentType, ContentType.Application.Json)
}
defaultRequest {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
}
}
Ktor로 요청 만들기
예시: GET 요청
suspend fun fetchLocationsList(): User = httpClient.get("https://api.example.com/locations/123").body()
예시: POST 요청
suspend fun createLocationList(location: Location): HttpResponse = httpClient.post("https://api.example.com/locations") {
contentType(ContentType.Application.Json)
setBody(location)
}
데이터 모델 생성
@Serializable
data class Location(
val locationId: Int,
val locationName: String,
val locationLatLong: String
)
Note: 직렬화 플러그인은 이미 앱 수준
build.gradle.kts에 추가되어 있습니다.
로깅 및 디버깅
Ktor의 내장 로깅 기능을 사용하면 Logcat에서 요청 및 응답을 모니터링할 수 있습니다. Koin이나 Hilt와 같은 DI 프레임워크와 원활하게 통합되며, Timber나 Klogging과 같은 로깅 라이브러리와 결합하여 더 풍부한 출력을 제공할 수 있습니다.
Final Thoughts
Retrofit은 전통적인 Android 앱에 여전히 견고하고 신뢰할 수 있는 선택이며, Ktor는 현대적이고 Kotlin‑first 및 멀티플랫폼 환경에서 빛을 발합니다. 위 단계들은 Ktor를 빠르게 시작하는 데 도움이 될 것입니다. 향후 기사에서는 의존성 주입(Koin)과 Timber를 활용한 고급 로깅에 대한 심층 통합을 다룰 예정입니다.
Ktor를 시도해보고 Kotlin‑first 개발의 유연성을 경험해 보세요.