Ktor 3.0.0-beta-2 Help

Default request

The DefaultRequest plugin allows you to configure default parameters for all requests: specify a base URL, add headers, configure query parameters, and so on.

Add dependencies

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

Install DefaultRequest

To install DefaultRequest, 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(DefaultRequest) }

... or call the defaultRequest function and configure required request parameters:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* //... val client = HttpClient(CIO) { defaultRequest { // this: DefaultRequestBuilder } }

Configure DefaultRequest

Base URL

DefaultRequest allows you to configure a base part of the URL that is merged with a request URL. For example, the url function below specifies a base URL for all requests:

defaultRequest { url("https://ktor.io/docs/") }

If you make the following request using the client with the above configuration, ...

val response: HttpResponse = client.get("welcome.html")

... the resulting URL will be the following: https://ktor.io/docs/welcome.html. To learn how base and request URLs are merged, see DefaultRequest.

URL parameters

The url function also allows you to specify URL components separately, for example:

  • an HTTP scheme;

  • a host name;

  • a base URL path;

  • a query parameter.

url { protocol = URLProtocol.HTTPS host = "ktor.io" path("docs/") parameters.append("token", "abc123") }

Headers

To add a specific header to each request, use the header function:

defaultRequest { header("X-Custom-Header", "Hello") }

To avoid duplicating headers, you can use the appendIfNameAbsent, appendIfNameAndValueAbsent, and contains functions:

defaultRequest { headers.appendIfNameAbsent("X-Custom-Header", "Hello") }

Example

The example below uses the following DefaultRequest configuration:

  • The url function defines an HTTP scheme, a host, a base URL path, and a query parameter.

  • The header function adds a custom header to all requests.

val client = HttpClient(CIO) { defaultRequest { url { protocol = URLProtocol.HTTPS host = "ktor.io" path("docs/") parameters.append("token", "abc123") } header("X-Custom-Header", "Hello") } }

The request below made by this client specifies a latter path segment only and applies parameters configured for DefaultRequest automatically:

val response: HttpResponse = client.get("welcome.html") println(response.status)

You can find the full example here: client-default-request.

Last modified: 02 April 2024