Ktor 1.5.4 Help

Timeout

The HttpTimeout feature allows you to configure the following timeouts:

  • request timeout — a time period required to process an HTTP call: from sending a request to receiving a response.

  • connection timeout — a time period in which a client should establish a connection with a server.

  • socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.

You can specify these timeouts for all requests or only specific ones.

Add dependencies

HttpTimeout only requires the ktor-client-core artifact and doesn't need any specific dependencies.

Install HttpTimeout

To install HttpTimeout, pass it to the install function inside a client configuration block:

val client = HttpClient(CIO) { install(HttpTimeout) }

Configure timeouts

To configure timeouts, you can use corresponding properties:

You can specify timeouts for all requests inside the install block. The code sample below shows how to set a request timout using requestTimeoutMillis:

val client = HttpClient(CIO) { install(HttpTimeout) { requestTimeoutMillis = 1000 } }

If you need to set a timeout only for a specific request, use the HttpRequestBuilder.timeout property:

val response: HttpResponse = client.get("http://0.0.0.0:8080/path1") { timeout { requestTimeoutMillis = 3000 } }

Note that timeouts specified for a specific request override global timeouts from the install block.

In a case of a timeout, Ktor throws HttpRequestTimeoutException, HttpConnectTimeoutException, or HttpSocketTimeoutException.

Limitations

HttpTimeout has some limitations for specific engines:

  • iOS doesn't support a connection timeout.

  • JavaScript supports only a request timeout.

  • Curl doesn't support a socket timeout.

Last modified: 19 April 2021