Cookies
The Ktor client allows you to handle cookies manually in the following ways:
The
cookie
function allows you to append a cookie to a specific request.The
setCookie
function enables you to parse theSet-Cookie
header value received in a response.
The HttpCookies plugin handles cookies automatically and keeps them between calls in storage. By default, it uses an in-memory storage, but you can also implement a persistent storage using CookiesStorage.
Add dependencies
HttpCookies
only requires the ktor-client-core artifact and doesn't need any specific dependencies.
Install and configure HttpCookies
To install HttpCookies
, pass it to the install
function inside a client configuration block:
This is enough to enable the Ktor client to keep cookies between requests. You can find the full example here: client-cookies.
The HttpCookies
plugin also allows you to add a specific set of cookies to each request by using ConstantCookiesStorage
. This might be useful in a test case that verifies a server response. The example below shows how to add a specified cookie to all requests for a specific domain:
Get cookies
The client provides the cookies
function to obtain all the cookies for the specified URL:
Custom cookie storage
If required, you can create a custom cookie storage by implementing the CookiesStorage interface:
You can use AcceptAllCookiesStorage as a reference.