JVM-specific HTTP utilities and extensions for the Ktor framework providing URL utilities, file content type detection, HTTP message properties, and content handling for JVM platforms
—
HTTP cookie creation, parsing, and rendering with encoding support, security options, and both client and server-side cookie handling.
Serializable cookie representation with comprehensive attributes and security options.
/**
* HTTP cookie representation
*/
data class Cookie(
val name: String,
val value: String,
val encoding: CookieEncoding = CookieEncoding.RAW,
val maxAgeInt: Int? = null,
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()
) : Serializable {
companion object {
fun serializer(): KSerializer<Cookie>
}
}Encoding strategies for cookie values to handle special characters and security.
/**
* Cookie value encoding strategies
*/
enum class CookieEncoding {
/**
* No encoding (raw value)
*/
RAW,
/**
* Double-quote the value
*/
DQUOTES,
/**
* Base64 encode the value
*/
BASE64_ENCODING,
/**
* URI encode the value
*/
URI_ENCODING
}Functions for rendering cookies in HTTP headers.
/**
* Render Set-Cookie header value
* @param cookie cookie to render
* @return Set-Cookie header value
*/
fun renderSetCookieHeader(cookie: Cookie): String
/**
* Render Set-Cookie header with individual parameters
* @param name cookie name
* @param value cookie value
* @param encoding value encoding strategy
* @param maxAge max age in seconds
* @param expires expiration date
* @param domain cookie domain
* @param path cookie path
* @param secure secure flag
* @param httpOnly HTTP-only flag
* @param extensions additional attributes
* @param includeEncoding whether to include encoding info
* @return Set-Cookie header value
*/
fun renderSetCookieHeader(
name: String,
value: String,
encoding: CookieEncoding = CookieEncoding.RAW,
maxAge: Int? = null,
expires: GMTDate? = null,
domain: String? = null,
path: String? = null,
secure: Boolean = false,
httpOnly: Boolean = false,
extensions: Map<String, String> = emptyMap(),
includeEncoding: Boolean = true
): String
/**
* Render Cookie header value (client-side)
* @param cookie cookie to render
* @return Cookie header value
*/
fun renderCookieHeader(cookie: Cookie): StringFunctions for parsing cookies from HTTP headers.
/**
* Parse Set-Cookie header value (server-side)
* @param headerValue Set-Cookie header value
* @return Cookie instance
*/
fun parseServerSetCookieHeader(headerValue: String): Cookie
/**
* Parse Cookie header value (client-side)
* @param headerValue Cookie header value
* @param decodeValues whether to decode values
* @return Map of cookie names to values
*/
fun parseClientCookiesHeader(
headerValue: String,
decodeValues: Boolean = true
): Map<String, String>Low-level functions for encoding and decoding cookie values.
/**
* Encode cookie value according to encoding strategy
* @param value value to encode
* @param encoding encoding strategy
* @return encoded value
*/
fun encodeCookieValue(value: String, encoding: CookieEncoding): String
/**
* Decode cookie value according to encoding strategy
* @param value encoded value
* @param encoding encoding strategy used
* @return decoded value
*/
fun decodeCookieValue(value: String, encoding: CookieEncoding): StringDate formatting and parsing specific to cookie expiration handling.
/**
* Convert cookie date string to GMTDate
* @param dateString cookie date string
* @return GMTDate instance
*/
fun fromCookieToGmtDate(dateString: String): GMTDate
/**
* Convert HTTP date string to GMTDate
* @param dateString HTTP date string
* @return GMTDate instance
*/
fun fromHttpToGmtDate(dateString: String): GMTDate
/**
* Convert GMTDate to HTTP date string
* @param date date to convert
* @return HTTP date string
*/
fun toHttpDate(date: GMTDate): StringUsage Examples:
import io.ktor.http.*
import io.ktor.util.date.*
// Create simple cookie
val sessionCookie = Cookie(
name = "sessionId",
value = "abc123def456",
httpOnly = true,
secure = true
)
// Create cookie with expiration
val persistentCookie = Cookie(
name = "remember_token",
value = "long-lived-token",
maxAgeInt = 30 * 24 * 3600, // 30 days
domain = ".example.com",
path = "/",
secure = true,
httpOnly = true
)
// Create cookie with custom attributes
val trackingCookie = Cookie(
name = "tracking",
value = "user-preferences",
extensions = mapOf(
"SameSite" to "Lax",
"Priority" to "High"
)
)
// Cookie with encoding for special characters
val encodedCookie = Cookie(
name = "data",
value = "value with spaces & symbols",
encoding = CookieEncoding.BASE64_ENCODING
)
// Render Set-Cookie headers (server-side)
val setCookieHeader1 = renderSetCookieHeader(sessionCookie)
// sessionId=abc123def456; HttpOnly; Secure
val setCookieHeader2 = renderSetCookieHeader(persistentCookie)
// remember_token=long-lived-token; Max-Age=2592000; Domain=.example.com; Path=/; HttpOnly; Secure
// Render Cookie header (client-side)
val cookieHeader = renderCookieHeader(sessionCookie)
// sessionId=abc123def456
// Parse Set-Cookie header
val setCookieValue = "user=john; Max-Age=3600; Path=/; HttpOnly"
val parsedCookie = parseServerSetCookieHeader(setCookieValue)
println("Name: ${parsedCookie.name}") // user
println("Value: ${parsedCookie.value}") // john
println("Max-Age: ${parsedCookie.maxAgeInt}") // 3600
println("HttpOnly: ${parsedCookie.httpOnly}") // true
// Parse client Cookie header
val clientCookieValue = "sessionId=abc123; userId=456; theme=dark"
val clientCookies = parseClientCookiesHeader(clientCookieValue)
clientCookies.forEach { (name, value) ->
println("$name = $value")
}
// Cookie value encoding/decoding
val originalValue = "user data with spaces"
val encoded = encodeCookieValue(originalValue, CookieEncoding.URI_ENCODING)
val decoded = decodeCookieValue(encoded, CookieEncoding.URI_ENCODING)
println("Original: $originalValue")
println("Encoded: $encoded")
println("Decoded: $decoded")
// Working with dates
val futureDate = GMTDate() + 7 * 24 * 3600 * 1000L // 7 days from now
val cookieWithExpiry = Cookie(
name = "temp_data",
value = "temporary",
expires = futureDate
)
// Date conversions
val httpDateString = toHttpDate(futureDate)
val cookieDateString = "Wed, 09 Jun 2021 10:18:14 GMT"
val parsedDate = fromCookieToGmtDate(cookieDateString)
// Cookie serialization (kotlinx.serialization support)
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class CookieContainer(val cookies: List<Cookie>)
val container = CookieContainer(listOf(sessionCookie, persistentCookie))
val json = Json.encodeToString(container)
val deserialized = Json.decodeFromString<CookieContainer>(json)
// Helper functions for common patterns
fun createSecureSessionCookie(sessionId: String): Cookie {
return Cookie(
name = "SESSIONID",
value = sessionId,
httpOnly = true,
secure = true,
path = "/",
extensions = mapOf("SameSite" to "Strict")
)
}
fun createRememberMeCookie(token: String, days: Int = 30): Cookie {
return Cookie(
name = "remember_me",
value = token,
maxAgeInt = days * 24 * 3600,
httpOnly = true,
secure = true,
path = "/",
extensions = mapOf("SameSite" to "Lax")
)
}
// Usage in HTTP responses
val headers = headers {
append(HttpHeaders.SetCookie, renderSetCookieHeader(sessionCookie))
append(HttpHeaders.SetCookie, renderSetCookieHeader(persistentCookie))
}
// Usage in HTTP requests
val requestHeaders = headers {
append(HttpHeaders.Cookie, renderCookieHeader(sessionCookie))
}
// Delete cookie by setting expired date
fun deleteCookie(name: String, domain: String? = null, path: String? = null): Cookie {
return Cookie(
name = name,
value = "",
expires = GMTDate(0), // Unix epoch
domain = domain,
path = path
)
}
val deleteCookie = deleteCookie("sessionId", path = "/")
val deleteHeader = renderSetCookieHeader(deleteCookie)
// sessionId=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/All types are defined above in their respective capability sections.
Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-http-jvm