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:
Or call the defaultRequest function and configure required request parameters:
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:
If you make the following request using the client with the above configuration, ...
... 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.
Headers
To add a specific header to each request, use the header function:
To avoid duplicating headers, you can use the appendIfNameAbsent, appendIfNameAndValueAbsent, and contains functions:
Unix domain sockets
You can build individual requests with Unix domain sockets, but you can also configure a default request with a socket parameter.
To do that, pass a unixSocket call with the path to the socket to the defaultRequest function, for example:
Example
The example below uses the following DefaultRequest configuration:
The
urlfunction defines an HTTP scheme, a host, a base URL path, and a query parameter.The
headerfunction adds a custom header to all requests.
The request below made by this client specifies a latter path segment only and applies parameters configured for DefaultRequest automatically:
You can find the full example here: client-default-request.