[Ktor] 3. Response

[Ktor] 3. Response

Ktor Client ๊ฐ€์ด๋“œ ์š”์•ฝ ์ •๋ฆฌ



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