Ktor 3.0.0-beta-1 Help

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 the Set-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:

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

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:

val client = HttpClient(CIO) { install(HttpCookies) { storage = ConstantCookiesStorage(Cookie(name = "user_name", value = "jetbrains", domain = "0.0.0.0")) } }

Get cookies

The client provides the cookies function to obtain all the cookies for the specified URL:

client.cookies("http://0.0.0.0:8080/")

Custom cookie storage

If required, you can create a custom cookie storage by implementing the CookiesStorage interface:

val client = HttpClient(CIO) { install(HttpCookies) { storage = CustomCookiesStorage() } } public class CustomCookiesStorage : CookiesStorage { // ... }

You can use AcceptAllCookiesStorage as a reference.

Last modified: 02 April 2024