KOTLIN · 파일/IO
Ktor 클라이언트
Ktor HTTP 클라이언트로 비동기 네트워크 요청을 수행합니다. 코루틴 기반의 간결한 API를 제공합니다.
파일/IO고급ktorhttp-clientasynccoroutines
핵심 설명
Ktor HTTP 클라이언트로 비동기 네트워크 요청을 수행합니다. 코루틴 기반의 간결한 API를 제공합니다.
Kotlin code
// build.gradle.kts:
// implementation("io.ktor:ktor-client-core:2.3.7")
// implementation("io.ktor:ktor-client-cio:2.3.7")
// implementation("io.ktor:ktor-client-content-negotiation:2.3.7")
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
suspend fun main() {
val client = HttpClient(CIO) {
engine {
requestTimeout = 10_000
}
}
client.use { c ->
// GET 요청
val response = c.get("https://httpbin.org/get") {
headers {
append("Accept", "application/json")
}
}
println("상태: ${response.status}")
println("응답: ${response.bodyAsText().take(200)}")
// POST 요청
val postResp = c.post("https://httpbin.org/post") {
setBody("""{"name": "kotlin"}""")
headers { append("Content-Type", "application/json") }
}
println("POST 상태: ${postResp.status}")
}
}학습 팁
client.use { }로 감싸면 블록 종료 시 HTTP 클라이언트가 자동으로 닫힙니다. 엔진 리소스 누수를 방지합니다.
주의할 점
Ktor 클라이언트를 요청마다 생성하면 성능이 저하됩니다. 앱 생명주기 동안 하나의 클라이언트를 재사용하세요.
자주 묻는 질문
Ktor 클라이언트란 무엇인가요?
Ktor HTTP 클라이언트로 비동기 네트워크 요청을 수행합니다. 코루틴 기반의 간결한 API를 제공합니다.
Ktor 클라이언트 학습 시 주의할 점은 무엇인가요?
Ktor 클라이언트를 요청마다 생성하면 성능이 저하됩니다. 앱 생명주기 동안 하나의 클라이언트를 재사용하세요.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.