Ktor 2.3.9 Help

Timeout

The HttpTimeout plugin 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:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* //... val client = HttpClient(CIO) { install(HttpTimeout) }

Configure timeouts

To configure timeouts, you can use corresponding properties:

  • requestTimeoutMillis specifies a timeout for a whole HTTP call, from sending a request to receiving a response.

  • connectTimeoutMillis specifies a timeout for establishing a connection with a server.

  • socketTimeoutMillis specifies a timeout for the maximum time in between two data packets when exchanging data with a server.

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, ConnectTimeoutException, or SocketTimeoutException.

Limitations

HttpTimeout has some limitations for specific engines:

  • Darwin doesn't support a connection timeout.

  • JavaScript supports only a request timeout.

  • Curl doesn't support a socket timeout.

Last modified: 11 January 2024