Skip to content

Latest commit

 

History

History
65 lines (46 loc) · 2.75 KB

http-cookies.md

File metadata and controls

65 lines (46 loc) · 2.75 KB
The HttpCookies plugin handles cookies automatically and keep them between calls in an in-memory storage.

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 keep them between calls in an in-memory storage.

Add dependencies {id="add_dependencies"}

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

Install and configure HttpCookies {id="install_plugin"}

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"))
    }
}

Get cookies {id="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 {id="custom_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.