ktor을 써야하는 이유 💡
- KMM을 사용해서 앱을 만든다고 생각해보자. ios에서는 java/android 기반인 Retrofit을 사용할 수 없다 .근데 ktor은 되는 모양…?
- 아래와 같이 종속성을 추가해줍시다
plugins {
...
kotlin("plugin.serialization") version "1.7.10"
...
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2")
implementation("io.ktor:ktor-client-core:$ktorVersion")
// CIO - for JVM and Android
implementation("io.ktor:ktor-client-cio:$ktorVersion")
implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
}
- 모든 데이터 클래스에 @SerialName & key_name 추가
@Serializable
data class Result(
@SerialName(value = "address_components")
val addressComponents: List? = null,
@SerialName(value = "adr_address")
val adrAddress: String? = null,
@SerialName(value = "formatted_address")
val formattedAddress: String,
@SerialName(value = "formatted_phone_number")
val formattedPhoneNumber: String? = null,
val geometry: Geometry
)
- call interface 변경
interface RetrofitPlaceDetailService {
@GET("/maps/api/place/details/json")
suspend fun getMapsApiPlaceDetails(
@Query("place_id") placeId: String,
@Query("key") key: String,
@Nullable @Query("language") language: String? = null
): Response
to
object HttpRoutes {
private const val BASE_URL = "https://maps.googleapis.com"
const val PLACE_DETAILS = "$BASE_URL/maps/api/place/details/json"
}
try {
val response: PlaceDetails? =
ktorClient.get(HttpRoutes.PLACE_DETAILS) {
parameter("place_id", placeId)
parameter("key", apiKey)
parameter("language", language)
}.body()
} catch (redirectResponseException: RedirectResponseException) {
} catch (clientRequestException: ClientRequestException) {
} catch (serverResponseException: ServerResponseException) {
}
...
- http client 객체 변경
val ktorClient = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
prettyPrint = true
isLenient = true
})
}
}
Uploaded by N2T