Ktor HTTP client core library - asynchronous framework for creating HTTP clients in Kotlin multiplatform
—
Cookie storage and management with configurable storage backends, automatic cookie handling, and support for session management.
Core plugin for automatic cookie management with configurable storage.
/**
* HTTP cookies management plugin
*/
class HttpCookies private constructor(
private val storage: CookiesStorage
) : Closeable {
/**
* Cookie plugin configuration
*/
class Config {
/** Cookie storage implementation */
var storage: CookiesStorage = AcceptAllCookiesStorage()
/**
* Add default cookies to storage
*/
fun default(block: suspend CookiesStorage.() -> Unit)
}
companion object : HttpClientPlugin<Config, HttpCookies> {
override val key: AttributeKey<HttpCookies> = AttributeKey("HttpCookies")
}
/**
* Get cookies for specific URL
*/
suspend fun get(requestUrl: Url): List<Cookie>
override fun close()
}Usage Examples:
import io.ktor.client.plugins.cookies.*
import io.ktor.http.*
val client = HttpClient {
install(HttpCookies) {
// Use default storage (accepts all cookies)
storage = AcceptAllCookiesStorage()
// Add default cookies
default {
addCookie("https://api.example.com", Cookie("session", "abc123"))
addCookie("https://api.example.com", Cookie("theme", "dark"))
}
}
}
// Cookies are automatically handled
val response1 = client.get("https://api.example.com/login") {
// Server sets cookies in response
}
// Cookies automatically sent with subsequent requests
val response2 = client.get("https://api.example.com/profile") {
// Cookies from previous response are included
}Interface for cookie storage implementations with lifecycle management.
/**
* Interface for cookie storage implementations
*/
interface CookiesStorage : Closeable {
/**
* Get cookies for specific URL
*/
suspend fun get(requestUrl: Url): List<Cookie>
/**
* Add cookie for specific URL
*/
suspend fun addCookie(requestUrl: Url, cookie: Cookie)
override fun close()
}
/**
* Extension function for adding cookies with URL string
*/
suspend fun CookiesStorage.addCookie(urlString: String, cookie: Cookie) {
addCookie(Url(urlString), cookie)
}Pre-built cookie storage implementations for common use cases.
/**
* Storage that accepts and stores all cookies
*/
class AcceptAllCookiesStorage : CookiesStorage {
override suspend fun get(requestUrl: Url): List<Cookie>
override suspend fun addCookie(requestUrl: Url, cookie: Cookie)
override fun close()
}
/**
* Storage with constant predefined cookies
*/
class ConstantCookiesStorage(cookies: List<Cookie>) : CookiesStorage {
override suspend fun get(requestUrl: Url): List<Cookie>
override suspend fun addCookie(requestUrl: Url, cookie: Cookie) {
// No-op - constants cannot be modified
}
override fun close()
}Usage Examples:
// Accept all cookies (default)
val client1 = HttpClient {
install(HttpCookies) {
storage = AcceptAllCookiesStorage()
}
}
// Constant cookies only
val constantCookies = listOf(
Cookie("auth_token", "xyz789"),
Cookie("user_preference", "compact_view")
)
val client2 = HttpClient {
install(HttpCookies) {
storage = ConstantCookiesStorage(constantCookies)
}
}
// Custom storage implementation
class MemoryCookieStorage : CookiesStorage {
private val cookies = mutableMapOf<String, MutableList<Cookie>>()
override suspend fun get(requestUrl: Url): List<Cookie> {
val host = requestUrl.host
return cookies[host]?.filter { cookie ->
// Apply cookie domain and path matching logic
cookieMatches(cookie, requestUrl)
} ?: emptyList()
}
override suspend fun addCookie(requestUrl: Url, cookie: Cookie) {
val host = requestUrl.host
cookies.getOrPut(host) { mutableListOf() }.add(cookie)
}
override fun close() {
cookies.clear()
}
}
val client3 = HttpClient {
install(HttpCookies) {
storage = MemoryCookieStorage()
}
}Functions for accessing cookies from HTTP client instances.
/**
* Get cookies for specific URL
*/
suspend fun HttpClient.cookies(url: Url): List<Cookie>
/**
* Get cookies for URL string
*/
suspend fun HttpClient.cookies(urlString: String): List<Cookie>
/**
* Get cookie by name from cookie list
*/
fun List<Cookie>.get(name: String): Cookie?Usage Examples:
val client = HttpClient {
install(HttpCookies)
}
// Make request that sets cookies
client.get("https://api.example.com/login")
// Access cookies
val cookies = client.cookies("https://api.example.com")
println("Found ${cookies.size} cookies")
// Find specific cookie
val sessionCookie = cookies.get("JSESSIONID")
if (sessionCookie != null) {
println("Session ID: ${sessionCookie.value}")
println("Expires: ${sessionCookie.expires}")
println("Secure: ${sessionCookie.secure}")
println("HttpOnly: ${sessionCookie.httpOnly}")
}
// Access cookies by URL
val apiCookies = client.cookies(Url("https://api.example.com/data"))
val userCookie = apiCookies.get("user_id")Advanced configuration options for cookie handling behavior.
/**
* Configure default cookies in HttpCookies plugin
*/
fun HttpCookies.Config.default(block: suspend CookiesStorage.() -> Unit)Usage Examples:
val client = HttpClient {
install(HttpCookies) {
// Custom storage
storage = AcceptAllCookiesStorage()
// Add default cookies that will be sent with all requests
default {
// Authentication cookie
addCookie(
"https://api.example.com",
Cookie(
name = "auth_token",
value = "bearer_xyz123",
domain = "api.example.com",
path = "/",
secure = true,
httpOnly = true
)
)
// User preference cookies
addCookie(
"https://api.example.com",
Cookie(
name = "theme",
value = "dark",
maxAge = 30 * 24 * 3600 // 30 days
)
)
// Session tracking
addCookie(
"https://api.example.com",
Cookie(
name = "session_id",
value = generateSessionId(),
expires = GMTDate() + 3600_000 // 1 hour
)
)
}
}
}Working with cookie attributes for security and behavior control.
/**
* Cookie class with all standard attributes
*/
data class Cookie(
val name: String,
val value: String,
val encoding: CookieEncoding = CookieEncoding.URI_ENCODING,
val maxAge: Int = 0,
val expires: GMTDate? = null,
val domain: String? = null,
val path: String? = null,
val secure: Boolean = false,
val httpOnly: Boolean = false,
val extensions: Map<String, String?> = emptyMap()
)Usage Examples:
// Create cookies with various attributes
val basicCookie = Cookie("user", "john_doe")
val secureCookie = Cookie(
name = "auth_token",
value = "secure_token_123",
secure = true, // HTTPS only
httpOnly = true, // Not accessible via JavaScript
domain = "example.com",
path = "/api",
maxAge = 3600 // 1 hour
)
val sessionCookie = Cookie(
name = "session",
value = "session_abc",
expires = GMTDate() + 86400_000, // 24 hours from now
path = "/"
)
// Persistent cookie with long expiration
val persistentCookie = Cookie(
name = "remember_me",
value = "true",
maxAge = 30 * 24 * 3600, // 30 days
secure = true,
extensions = mapOf(
"SameSite" to "Strict"
)
)
// Add cookies to storage
val storage = AcceptAllCookiesStorage()
storage.addCookie("https://api.example.com", secureCookie)
storage.addCookie("https://api.example.com", sessionCookie)
storage.addCookie("https://api.example.com", persistentCookie)Manual cookie handling for advanced use cases.
/**
* Access cookie storage directly from client
*/
val HttpClient.cookies: HttpCookies?
get() = pluginOrNull(HttpCookies)Usage Examples:
val client = HttpClient {
install(HttpCookies)
}
// Direct access to cookie plugin
val cookiePlugin = client.plugin(HttpCookies)
// Manual cookie management
val customCookies = listOf(
Cookie("custom1", "value1"),
Cookie("custom2", "value2")
)
// Add cookies manually before request
customCookies.forEach { cookie ->
cookiePlugin.storage.addCookie("https://api.example.com", cookie)
}
// Make request with manually added cookies
val response = client.get("https://api.example.com/data")
// Inspect response cookies
val responseCookies = response.setCookie()
responseCookies.forEach { cookie ->
println("Server set cookie: ${cookie.name} = ${cookie.value}")
}Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-client-core-iosx64