Ktor HTTP client core library providing asynchronous HTTP client functionality for multiplatform applications with macOS ARM64 support.
—
Request building DSL for constructing HTTP requests with headers, parameters, body content, and various configuration options using a fluent API.
Main request builder providing a DSL for configuring HTTP requests.
/**
* Builder for constructing HTTP requests with fluent API
*/
class HttpRequestBuilder {
/** HTTP method for the request */
var method: HttpMethod
/** URL builder for constructing request URL */
val url: URLBuilder
/** Headers builder for request headers */
val headers: HeadersBuilder
/** Request body content */
var body: Any
/** Request attributes for storing custom data */
val attributes: Attributes
/** Execution context for the request */
var executionContext: Job?
/** Set single header value */
fun header(key: String, value: String)
/** Configure headers using builder DSL */
fun headers(block: HeadersBuilder.() -> Unit)
/** Add URL parameter */
fun parameter(key: String, value: Any?)
/** Set Accept header */
fun accept(contentType: ContentType)
/** Set Accept-Charset header */
fun acceptCharset(charset: Charset)
/** Set Accept-Encoding header */
fun acceptEncoding(encoding: String)
/** Set Accept-Language header */
fun acceptLanguage(language: String)
/** Set Accept-Ranges header */
fun acceptRanges(ranges: String)
/** Set Cache-Control header */
fun cacheControl(cacheControl: CacheControl)
/** Set Content-Length header */
fun contentLength(length: Long)
/** Set Content-Type header */
fun contentType(contentType: ContentType)
/** Add cookie to request */
fun cookie(name: String, value: String, encoding: CookieEncoding = CookieEncoding.URI_ENCODING)
/** Set Host header */
fun host(host: String)
/** Set port for the request URL */
fun port(port: Int)
/** Set User-Agent header */
fun userAgent(agent: String)
/** Set Basic authentication header */
fun basicAuth(username: String, password: String)
/** Set Bearer token authentication header */
fun bearerAuth(token: String)
/** Configure request timeout */
fun timeout(block: HttpTimeoutCapabilityConfiguration.() -> Unit)
/** Build the final request data */
fun build(): HttpRequestData
}Usage Examples:
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
val client = HttpClient()
// Basic request building
val response = client.request {
method = HttpMethod.Post
url("https://api.example.com/users")
headers {
append("Content-Type", "application/json")
append("Accept", "application/json")
}
setBody("""{"name": "John", "email": "john@example.com"}""")
}
// Advanced request configuration
val advancedResponse = client.request {
method = HttpMethod.Get
url {
protocol = URLProtocol.HTTPS
host = "api.example.com"
path("v1", "users")
parameter("page", 1)
parameter("limit", 10)
parameter("sort", "name")
}
headers {
append("Authorization", "Bearer $token")
append("Accept", "application/vnd.api+json")
append("User-Agent", "MyApp/1.0")
}
timeout {
requestTimeoutMillis = 30000
connectTimeoutMillis = 10000
}
}URL building capabilities for constructing request URLs with parameters and path segments.
/**
* URL builder for constructing request URLs
*/
class URLBuilder {
/** URL protocol (HTTP, HTTPS) */
var protocol: URLProtocol
/** Host name */
var host: String
/** Port number */
var port: Int
/** URL path segments */
val pathSegments: MutableList<String>
/** URL parameters */
val parameters: ParametersBuilder
/** URL fragment */
var fragment: String
/** Username for authentication */
var user: String?
/** Password for authentication */
var password: String?
/** Append path segments */
fun path(vararg components: String)
/** Set or append path segments */
fun appendPath(path: String)
/** Add URL parameter */
fun parameter(name: String, value: Any?)
/** Build final URL */
fun build(): Url
}
/**
* Configure URL in request builder
* @param block URL configuration block
*/
fun HttpRequestBuilder.url(block: URLBuilder.() -> Unit)
/**
* Set URL from string
* @param urlString URL string to parse
*/
fun HttpRequestBuilder.url(urlString: String)Usage Examples:
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
val client = HttpClient()
// URL building with DSL
val response = client.get {
url {
protocol = URLProtocol.HTTPS
host = "api.github.com"
path("repos", "ktorio", "ktor", "issues")
parameter("state", "open")
parameter("labels", "bug")
parameter("per_page", 50)
}
}
// URL building with string base
val response2 = client.post("https://api.example.com/data") {
url {
parameter("format", "json")
parameter("timestamp", System.currentTimeMillis())
}
setBody(requestData)
}
// Complex URL construction
val response3 = client.request {
method = HttpMethod.Get
url {
protocol = URLProtocol.HTTPS
host = "api.example.com"
port = 443
path("v2", "search", "repositories")
parameter("q", "language:kotlin")
parameter("sort", "stars")
parameter("order", "desc")
fragment = "results"
}
}Header management for setting and configuring HTTP request headers.
/**
* Headers builder for managing request headers
*/
class HeadersBuilder : StringValuesBuilder {
/** Append header value */
fun append(name: String, value: String)
/** Set header value (replace existing) */
fun set(name: String, value: String)
/** Remove header */
fun remove(name: String)
/** Append all headers from another headers collection */
fun appendAll(headers: Headers)
/** Check if header exists */
fun contains(name: String): Boolean
/** Get header values */
fun getAll(name: String): List<String>?
/** Build final headers */
fun build(): Headers
}
/**
* Convenient header setting functions in HttpRequestBuilder
*/
fun HttpRequestBuilder.header(key: String, value: String)
fun HttpRequestBuilder.headers(block: HeadersBuilder.() -> Unit)
fun HttpRequestBuilder.accept(contentType: ContentType)
fun HttpRequestBuilder.acceptCharset(charset: Charset)
fun HttpRequestBuilder.acceptEncoding(encoding: String)
fun HttpRequestBuilder.acceptLanguage(language: String)
fun HttpRequestBuilder.acceptRanges(ranges: String)
fun HttpRequestBuilder.cacheControl(cacheControl: CacheControl)
fun HttpRequestBuilder.contentLength(length: Long)
fun HttpRequestBuilder.contentType(contentType: ContentType)
fun HttpRequestBuilder.userAgent(agent: String)Usage Examples:
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
val client = HttpClient()
// Basic header configuration
val response = client.post("https://api.example.com/data") {
headers {
append("Content-Type", "application/json")
append("Accept", "application/json")
append("Authorization", "Bearer $token")
append("X-Client-Version", "1.0.0")
}
setBody(jsonData)
}
// Convenient header functions
val response2 = client.get("https://api.example.com/data") {
accept(ContentType.Application.Json)
contentType(ContentType.Application.Json)
userAgent("MyApp/1.0 (Platform/Version)")
acceptEncoding("gzip, deflate")
acceptLanguage("en-US,en;q=0.9")
header("X-API-Key", apiKey)
header("X-Request-ID", requestId)
}
// Conditional headers
val response3 = client.request {
method = HttpMethod.Get
url("https://api.example.com/resource")
headers {
append("Accept", "application/json")
if (authToken != null) {
append("Authorization", "Bearer $authToken")
}
if (etag != null) {
append("If-None-Match", etag)
}
append("Cache-Control", "max-age=300")
}
}Authentication helpers for setting various authentication headers.
/**
* Set Basic authentication header
* @param username Username for authentication
* @param password Password for authentication
*/
fun HttpRequestBuilder.basicAuth(username: String, password: String)
/**
* Set Bearer token authentication header
* @param token Bearer token value
*/
fun HttpRequestBuilder.bearerAuth(token: String)
/**
* Add cookie to request
* @param name Cookie name
* @param value Cookie value
* @param encoding Cookie encoding method
*/
fun HttpRequestBuilder.cookie(
name: String,
value: String,
encoding: CookieEncoding = CookieEncoding.URI_ENCODING
)Usage Examples:
import io.ktor.client.*
import io.ktor.client.request.*
val client = HttpClient()
// Basic authentication
val basicResponse = client.get("https://api.example.com/protected") {
basicAuth("username", "password")
}
// Bearer token authentication
val bearerResponse = client.get("https://api.example.com/protected") {
bearerAuth("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
}
// Cookie authentication
val cookieResponse = client.get("https://example.com/dashboard") {
cookie("session_id", "abc123def456")
cookie("preferences", "theme=dark&lang=en")
}
// Custom authentication header
val customResponse = client.get("https://api.example.com/data") {
header("X-API-Key", "your-api-key-here")
header("X-Auth-Token", "custom-token-format")
}Request body setting for various content types and data formats.
/**
* Set request body content
* @param body Body content (String, ByteArray, OutgoingContent, etc.)
*/
fun HttpRequestBuilder.setBody(body: Any?)
/** Request body property */
var HttpRequestBuilder.body: AnyUsage Examples:
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.utils.io.*
val client = HttpClient()
// JSON body
val jsonResponse = client.post("https://api.example.com/users") {
contentType(ContentType.Application.Json)
setBody("""{"name": "John", "email": "john@example.com"}""")
}
// Text body
val textResponse = client.post("https://api.example.com/notes") {
contentType(ContentType.Text.Plain)
setBody("This is a plain text note")
}
// Binary body
val binaryData = byteArrayOf(0x89, 0x50, 0x4E, 0x47) // PNG header example
val binaryResponse = client.post("https://api.example.com/upload") {
contentType(ContentType.Application.OctetStream)
setBody(binaryData)
}
// Custom content
val customContent = object : OutgoingContent.WriteChannelContent() {
override val contentType = ContentType.Application.Json
override val contentLength = jsonData.length.toLong()
override suspend fun writeTo(channel: ByteWriteChannel) {
channel.writeStringUtf8(jsonData)
}
}
val customResponse = client.post("https://api.example.com/custom") {
setBody(customContent)
}Request timeout configuration for controlling request timing behavior.
/**
* Configure request timeout settings
* @param block Timeout configuration block
*/
fun HttpRequestBuilder.timeout(block: HttpTimeoutCapabilityConfiguration.() -> Unit)
/**
* Timeout configuration options
*/
class HttpTimeoutCapabilityConfiguration {
/** Request timeout in milliseconds */
var requestTimeoutMillis: Long?
/** Connection timeout in milliseconds */
var connectTimeoutMillis: Long?
/** Socket timeout in milliseconds */
var socketTimeoutMillis: Long?
}Usage Examples:
import io.ktor.client.*
import io.ktor.client.request.*
val client = HttpClient()
// Basic timeout configuration
val response = client.get("https://slow-api.example.com/data") {
timeout {
requestTimeoutMillis = 30000 // 30 seconds
connectTimeoutMillis = 10000 // 10 seconds
socketTimeoutMillis = 20000 // 20 seconds
}
}
// Different timeouts for different operations
val uploadResponse = client.post("https://api.example.com/upload") {
setBody(largeFileData)
timeout {
requestTimeoutMillis = 300000 // 5 minutes for uploads
connectTimeoutMillis = 15000 // 15 seconds to connect
}
}
// No timeout (infinite)
val longRunningResponse = client.get("https://api.example.com/long-process") {
timeout {
requestTimeoutMillis = null // No request timeout
}
}class HttpRequestData(
val url: Url,
val method: HttpMethod,
val headers: Headers,
val body: OutgoingContent,
val executionContext: Job,
val attributes: Attributes
)
enum class CookieEncoding {
URI_ENCODING,
DQUOTES,
RAW
}
class CacheControl(
val value: String
) {
companion object {
val NoCache = CacheControl("no-cache")
val NoStore = CacheControl("no-store")
val MaxAge = { seconds: Int -> CacheControl("max-age=$seconds") }
}
}class ParametersBuilder(size: Int = 8) : StringValuesBuilder {
fun append(name: String, value: String)
fun appendAll(stringValues: StringValues)
fun appendAll(name: String, values: Iterable<String>)
fun appendMissing(stringValues: StringValues)
fun appendMissing(name: String, values: Iterable<String>)
fun set(name: String, value: String)
fun setAll(stringValues: StringValues)
fun setAll(name: String, values: Iterable<String>)
fun remove(name: String): Boolean
fun removeKeysWithNoEntries()
fun clear()
fun build(): Parameters
}
interface Parameters : StringValues {
companion object {
val Empty: Parameters
}
}Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-client-core-macosarm64