Ktor 3.0.0-beta-2 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 the 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. The table below shows which timeouts are supported by those engines:

Engine

Request Timeout

Connect Timeout

Socket Timeout

Darwin

✅️

✖️

✅️

JavaScript

✖️

✖️

Curl

✅️

✖️

MockEngine

✖️

Last modified: 10 May 2024