Http Client

In addition to HTTP serving, Ktor also includes a flexible asynchronous HTTP client.This client supports several configurable engines, and has its own set of features.

The main functionality is available through the io.ktor:ktor-client-core:$ktor_version artifact.And each engine, is provided in separate artifacts.

Table of contents:

Calls: Requests and Responses

You can check how to make requests,and how to receive responses in their respective sections.

Concurrency

Remember that requests are asynchronous, but when performing requests, the API suspends further requestsand your function will be suspended until done. If you want to perform several requests at oncein the same block, you can use launch or async functions and later get the results.For example:

Sequential requests

  1. suspend fun sequentialRequests() {
  2. val client = HttpClient()
  3. // Get the content of an URL.
  4. val firstBytes = client.get<ByteArray>("https://127.0.0.1:8080/a")
  5. // Once the previous request is done, get the content of an URL.
  6. val secondBytes = client.get<ByteArray>("https://127.0.0.1:8080/b")
  7. client.close()
  8. }

Parallel requests

  1. suspend fun parallelRequests() = coroutineScope<Unit> {
  2. val client = HttpClient()
  3. // Start two requests asynchronously.
  4. val firstRequest = async { client.get<ByteArray>("https://127.0.0.1:8080/a") }
  5. val secondRequest = async { client.get<ByteArray>("https://127.0.0.1:8080/b") }
  6. // Get the request contents without blocking threads, but suspending the function until both
  7. // requests are done.
  8. val bytes1 = firstRequest.await() // Suspension point.
  9. val bytes2 = secondRequest.await() // Suspension point.
  10. client.close()
  11. }

Examples

For more information, check the examples page with some examples.

Features

For more information, check the features page with all the available features.