CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-client-core-tvosarm64

Ktor HTTP Client Core for tvOS ARM64 - multiplatform asynchronous HTTP client library with coroutines support

Pending
Overview
Eval results
Files

request-building.mddocs/

Request Building

The request building API provides a type-safe DSL for constructing HTTP requests with comprehensive configuration options for URLs, headers, parameters, and body content.

Core Types

class HttpRequestBuilder : HttpMessageBuilder {
    public var method: HttpMethod = HttpMethod.Get
    public val url: URLBuilder = URLBuilder()
    public override val headers: HeadersBuilder = HeadersBuilder()
    public var body: Any = EmptyContent
    public var bodyType: TypeInfo?
    public var executionContext: Job = SupervisorJob()
    public val attributes: Attributes = Attributes(concurrent = true)
    
    public fun url(block: URLBuilder.(URLBuilder) -> Unit): Unit
}

// Extension functions for HttpRequestBuilder
fun HttpRequestBuilder.url(url: String)
fun HttpRequestBuilder.url(url: Url)
fun HttpRequestBuilder.url(
    scheme: String? = null,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    block: URLBuilder.() -> Unit = {}
)

var HttpRequestBuilder.host: String
var HttpRequestBuilder.port: Int

fun HttpRequestBuilder.parameter(key: String, value: Any?)

// Extension functions for HttpMessageBuilder (inherited by HttpRequestBuilder)
fun HttpMessageBuilder.header(key: String, value: Any?)
fun HttpMessageBuilder.cookie(
    name: String,
    value: String,
    maxAge: Int = 0,
    expires: GMTDate? = null,
    domain: String? = null,
    path: String? = null,
    secure: Boolean = false,
    httpOnly: Boolean = false,
    extensions: Map<String, String?> = emptyMap()
)
fun HttpMessageBuilder.accept(contentType: ContentType)
fun HttpMessageBuilder.basicAuth(username: String, password: String)
fun HttpMessageBuilder.bearerAuth(token: String)

// Body setting functions
inline fun <reified T> HttpRequestBuilder.setBody(body: T)
fun HttpRequestBuilder.setBody(body: Any?, bodyType: TypeInfo)

interface HttpRequest : HttpMessage, CoroutineScope { val call: HttpClientCall val method: HttpMethod val url: Url val attributes: Attributes val content: OutgoingContent }

## URL Configuration

### Basic URL Setting
```kotlin
client.request {
    url("https://api.example.com/users/123")
}

URL Components

client.request {
    url {
        protocol = URLProtocol.HTTPS
        host = "api.example.com"
        port = 443
        path("users", "123")
    }
}

URL Parameters

client.request {
    url("https://api.example.com/users")
    parameter("page", 1)
    parameter("limit", 10)
    parameter("sort", "name")
    parameter("fields", listOf("id", "name", "email"))
}
// Results in: https://api.example.com/users?page=1&limit=10&sort=name&fields=id&fields=name&fields=email

Headers Configuration

Individual Headers

client.request {
    header("Authorization", "Bearer $token")
    header("X-Custom-Header", "custom-value")
    accept(ContentType.Application.Json)
    contentType(ContentType.Application.Json)
    userAgent("MyApp/1.0")
}

Headers Block

client.request {
    headers {
        append("X-Request-ID", requestId)
        append("X-Client-Version", "1.2.3")
        if (debugMode) {
            append("X-Debug", "true")
        }
    }
}

Authentication Headers

// Basic authentication
client.request {
    basicAuth("username", "password")
}

// Bearer token
client.request {
    bearerAuth("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
}

Request Body

JSON Body

client.request {
    method = HttpMethod.Post
    contentType(ContentType.Application.Json)
    setBody("""{"name": "John", "email": "john@example.com"}""")
}

Serializable Object Body

@Serializable
data class User(val name: String, val email: String)

client.request {
    method = HttpMethod.Post
    contentType(ContentType.Application.Json)
    setBody(User("John", "john@example.com"))
}

Form Data Body

client.request {
    method = HttpMethod.Post
    setBody(FormDataContent(Parameters.build {
        append("name", "John")
        append("email", "john@example.com")
    }))
}

Multipart Form Body

client.request {
    method = HttpMethod.Post
    setBody(MultiPartFormDataContent(
        formData {
            append("name", "John")
            append("file", "document.pdf", ContentType.Application.Pdf) {
                writeFully(fileBytes)
            }
        }
    ))
}

Binary Body

client.request {
    method = HttpMethod.Put
    contentType(ContentType.Application.OctetStream)
    setBody(byteArrayOf(0x01, 0x02, 0x03))
}

Channel Body

client.request {
    method = HttpMethod.Post
    setBody(object : OutgoingContent.WriteChannelContent() {
        override suspend fun writeTo(channel: ByteWriteChannel) {
            channel.writeStringUtf8("streaming data")
            channel.close()
        }
    })
}

HTTP Methods

Setting Method Explicitly

client.request {
    method = HttpMethod.Patch
    url("https://api.example.com/users/123")
    setBody("""{"name": "Updated Name"}""")
}

Custom HTTP Methods

val customMethod = HttpMethod("CUSTOM")
client.request {
    method = customMethod
    url("https://api.example.com/custom-endpoint")
}

Request Attributes

Attributes allow storing custom data with requests:

val RequestIdKey = AttributeKey<String>("RequestId")

client.request {
    attributes.put(RequestIdKey, "req-123")
    url("https://api.example.com/users")
}

// Access in plugins or interceptors
val requestId = request.attributes[RequestIdKey]

Timeout Configuration

With the HttpTimeout plugin installed:

client.request {
    timeout {
        requestTimeoutMillis = 30000
        connectTimeoutMillis = 10000
        socketTimeoutMillis = 20000
    }
    url("https://slow-api.example.com")
}

Unix Socket Requests

Support for Unix domain sockets:

client.request {
    url.protocol = URLProtocol.createOrDefault("unix")
    url.host = "/tmp/socket"
    url.encodedPath = "/path"
}

Advanced URL Building

Path Segments

client.request {
    url {
        appendPathSegments("users", userId.toString(), "profile")
    }
}

Encoded Parameters

client.request {
    url {
        parameters.append("query", "hello world") // Automatically encoded
        parameters.appendAll("tags", listOf("kotlin", "http"))
    }
}

Fragment

client.request {
    url {
        fragment = "section1"
    }
}

Request Validation

URL Validation

try {
    client.request {
        url("not-a-valid-url")
    }
} catch (e: URLParserException) {
    println("Invalid URL: ${e.message}")
}

Content Type Validation

client.request {
    // Ensure Content-Type matches body type
    contentType(ContentType.Application.Json)
    setBody(jsonString) // Must be valid JSON
}

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-client-core-tvosarm64

docs

builtin-plugins.md

caching.md

cookies.md

engine-configuration.md

forms.md

http-client.md

index.md

plugin-system.md

request-building.md

response-handling.md

response-observation.md

utilities.md

websockets.md

tile.json