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 keep them between calls in an in-memory storage.
HttpCookies
only requires the ktor-client-core artifact and doesn't need any specific dependencies.
To install HttpCookies
, pass it to the install
function inside a client configuration block:
{src="snippets/client-cookies/src/main/kotlin/com/example/Application.kt" lines="12-14"}
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"))
}
}
The client provides the cookies
function to obtain all the cookies for the specified URL:
client.cookies("http://0.0.0.0:8080/")
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.