Skip to content

Latest commit

 

History

History
101 lines (64 loc) · 3.12 KB

default-request.md

File metadata and controls

101 lines (64 loc) · 3.12 KB
The DefaultRequest plugin allows you to configure default parameters for all requests.

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

Add dependencies {id="add_dependencies"}

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

Install DefaultRequest {id="install_plugin"}

To install DefaultRequest, pass it to the install function inside a client configuration block ...

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

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

val client = HttpClient(CIO) {
    defaultRequest {
        // this: HttpRequestBuilder
    }
}

Configure DefaultRequest {id="configure"}

Base URL {id="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, ...

{src="snippets/client-default-request/src/main/kotlin/com/example/Application.kt" lines="24"}

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

Add headers {id="headers"}

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

{src="snippets/client-default-request/src/main/kotlin/com/example/Application.kt" lines="14,20-21"}

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

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

Example {id="example"}

The example below uses the following DefaultRequest configuration:

  • The url function defines an HTTP scheme, a host, and a base URL path.
  • The header function adds a custom header to all requests.

{src="snippets/client-default-request/src/main/kotlin/com/example/Application.kt" lines="13-22"}

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

{src="snippets/client-default-request/src/main/kotlin/com/example/Application.kt" lines="24-25"}

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