[Ktor] 3. Response
Ktor Client ๊ฐ์ด๋ ์์ฝ ์ ๋ฆฌ
- Ktor Documents
- ๊ธฐ์ค ๋ฒ์ :
1.6.2
- ์๋ฆฌ์ฆ
Request๋ฅผ ์์ฑํ๋ ๋ชจ๋ ํจ์(request
, get
, post
, โฆ)๋ HttpResponse
๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค.
Response body
Raw body
- String
val httpResponse: HttpResponse = client.get("https://ktor.io/") val stringBody: String = httpResponse.receive()
- ByteArray
val httpResponse: HttpResponse = client.get("https://ktor.io/") val byteArrayBody: ByteArray = httpResponse.receive()
- ByteArray ํ์ ์ผ๋ก ๋ฐ์์ ํ์ผ๋ก ์ ์ฅํ๊ธฐ (์คํ ๊ฐ๋ฅ ์์ ๋งํฌ)
val client = HttpClient()
val file = File.createTempFile("files", "index")
runBlocking {
val httpResponse: HttpResponse = client.get("https://ktor.io/") {
// onDownload: download progress callback
onDownload { bytesSentTotal, contentLength ->
println("Received $bytesSentTotal bytes from $contentLength")
}
}
val responseBody: ByteArray = httpResponse.receive()
file.writeBytes(responseBody)
println("A file saved to ${file.path}")
}
Json object
JSON ํ๋ฌ๊ทธ์ธ์ ์ด์ฉํ๋ฉด JSON ๋ฐ์ดํฐ๋ฅผ data class๋ก deserialize ๊ฐ๋ฅํ๋ค.
val customer: Customer = client.get("http://127.0.0.1:8080/customer")
Streaming data
HttpResponse.receive
ํจ์๋ฅผ ํธ์ถํ๋ฉด Ktor๋ ์๋ต์ ๋ฉ๋ชจ๋ฆฌ์์ ์ฒ๋ฆฌํ์ฌ ์ ์ฒด response body๋ฅผ ๋ฐํํ๋ค. ์ ์ฒด ์๋ต์ ๊ธฐ๋ค๋ฆฌ๋ ๊ฒ์ด ์๋, ์์ฐจ์ ์ธ chunk๋ฅผ ์ป์ผ๋ ค๋ฉด HttpStatement
๋ฅผ ๋ฐํํ๋ execute
block์ ์ด์ฉํ๋ค.
val client = HttpClient(CIO)
val file = File.createTempFile("files", "index")
runBlocking {
client.get<HttpStatement>("https://ktor.io/").execute { httpResponse ->
val channel: ByteReadChannel = httpResponse.receive()
while (!channel.isClosedForRead) {
val packet = channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong())
while (!packet.isEmpty) {
val bytes = packet.readBytes()
file.appendBytes(bytes)
println("Received ${file.length()} bytes from ${httpResponse.contentLength()}")
}
}
println("A file saved to ${file.path}")
}
}
Response parameters
HttpResponse
ํด๋์ค๋ status code, headers, HTTP version ๋ฑ์ ํ๋ผ๋ฏธํฐ๋ฅผ ์ ๊ณตํ๋ค.
Status code
HttpResponse.status
ํ๋กํผํฐ
Headers
HttpResponse.headers
ํ๋กํผํฐ
Comments