CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Ktor HTTP Client Core - a multiplatform asynchronous HTTP client library for Kotlin providing comprehensive HTTP request/response handling with plugin architecture.

Pending
Overview
Eval results
Files

http-requests.mddocs/

HTTP Requests

Comprehensive HTTP request functionality including all standard methods, request building, URL construction, and parameter handling.

Capabilities

HTTP Method Functions

Standard HTTP method convenience functions for making requests.

/**
 * Make a GET request
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.get(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

/**
 * Make a POST request
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.post(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

/**
 * Make a PUT request
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.put(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

/**
 * Make a DELETE request
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.delete(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

/**
 * Make a HEAD request
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.head(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

/**
 * Make a PATCH request
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.patch(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

/**
 * Make an OPTIONS request
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.options(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

Usage Examples:

val client = HttpClient()

// Simple GET request
val response = client.get("https://api.example.com/users")

// POST with JSON body
val postResponse = client.post("https://api.example.com/users") {
    setBody("""{"name": "John", "email": "john@example.com"}""")
    header("Content-Type", "application/json")
}

// PUT with parameters
val putResponse = client.put("https://api.example.com/users/123") {
    parameter("version", "2")
    setBody("""{"name": "Jane", "email": "jane@example.com"}""")
}

// DELETE with authentication
val deleteResponse = client.delete("https://api.example.com/users/123") {
    bearerAuth("your-token-here")
}

Request Preparation Functions

Prepare requests without immediately executing them.

/**
 * Prepare a GET request without executing it
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.prepareGet(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpStatement

/**
 * Prepare a POST request without executing it
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.preparePost(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpStatement

/**
 * Prepare a PUT request without executing it
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.preparePut(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpStatement

/**
 * Prepare a DELETE request without executing it
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.prepareDelete(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpStatement

/**
 * Prepare a HEAD request without executing it
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.prepareHead(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpStatement

/**
 * Prepare a PATCH request without executing it
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.preparePatch(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpStatement

/**
 * Prepare an OPTIONS request without executing it
 * @param urlString Target URL
 * @param block Optional request configuration
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.prepareOptions(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpStatement

/**
 * Prepare a generic request without executing it
 * @param block Request configuration including method and URL
 * @returns HttpStatement ready for execution
 */
suspend fun HttpClient.prepareRequest(block: HttpRequestBuilder.() -> Unit): HttpStatement

Usage Examples:

// Prepare request for later execution
val statement = client.prepareGet("https://api.example.com/users") {
    parameter("page", "1")
    header("Accept", "application/json")
}

// Execute when ready
val response = statement.execute()

// Or execute with custom response handling
val result = statement.execute { response ->
    response.bodyAsText()
}

Generic Request Functions

Generic request methods for custom HTTP methods and advanced configuration.

/**
 * Make a generic HTTP request
 * @param block Request configuration including method, URL, and options
 * @returns HttpResponse
 */
suspend fun HttpClient.request(block: HttpRequestBuilder.() -> Unit): HttpResponse

/**
 * Make a generic HTTP request with URL
 * @param urlString Target URL
 * @param block Request configuration
 * @returns HttpResponse
 */
suspend fun HttpClient.request(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

Usage Examples:

// Custom HTTP method
val response = client.request {
    method = HttpMethod.Parse("CUSTOM")
    url("https://api.example.com/custom-endpoint")
    setBody("custom body")
}

// Complex request configuration
val complexResponse = client.request("https://api.example.com/data") {
    method = HttpMethod.Get
    parameter("filter", "active")
    parameter("sort", "name")
    headers {
        append("Custom-Header", "value")
        append("Accept-Language", "en-US")
    }
    timeout {
        requestTimeoutMillis = 60000
    }
}

HttpRequestBuilder Class

Main class for building HTTP requests with comprehensive configuration options.

/**
 * Builder class for constructing HTTP requests
 */
class HttpRequestBuilder {
    /** HTTP method for the request */
    var method: HttpMethod
    
    /** Request body content */
    var body: Any?
    
    /** Request headers */
    val headers: HeadersBuilder
    
    /** URL components */
    val url: URLBuilder
    
    /** Request attributes for plugins */
    val attributes: Attributes
    
    /**
     * Set the request body
     * @param body Body content (String, ByteArray, OutgoingContent, etc.)
     */
    fun setBody(body: Any?)
    
    /**
     * Add a URL parameter
     * @param key Parameter name
     * @param value Parameter value
     */
    fun parameter(key: String, value: Any?)
    
    /**
     * Add a request header
     * @param key Header name
     * @param value Header value
     */
    fun header(key: String, value: String)
    
    /**
     * Configure headers using a builder
     * @param block Header configuration block
     */
    fun headers(block: HeadersBuilder.() -> Unit)
    
    /**
     * Configure URL using a builder
     * @param block URL configuration block
     */
    fun url(block: URLBuilder.() -> Unit)
    
    /**
     * Set Content-Type header
     * @param contentType Content type value
     */
    fun contentType(contentType: ContentType)
    
    /**
     * Set Accept header
     * @param contentType Accepted content type
     */
    fun accept(contentType: ContentType)
    
    /**
     * Set Bearer token authorization
     * @param token Bearer token
     */
    fun bearerAuth(token: String)
    
    /**
     * Set Basic authentication
     * @param username Username
     * @param password Password
     */
    fun basicAuth(username: String, password: String)
    
    /**
     * Configure request timeout
     * @param block Timeout configuration
     */
    fun timeout(block: HttpTimeoutCapabilityConfiguration.() -> Unit)
}

Usage Examples:

val response = client.post("https://api.example.com/data") {
    // Set request method (usually inferred from function)
    method = HttpMethod.Post
    
    // Configure URL
    url {
        protocol = URLProtocol.HTTPS
        host = "api.example.com"
        path("data", "upload")
        parameter("version", "2")
    }
    
    // Set headers
    header("Custom-Header", "value")
    headers {
        append("Accept", "application/json")
        append("User-Agent", "MyApp/1.0")
    }
    
    // Set body
    setBody("""{"data": "example"}""")
    contentType(ContentType.Application.Json)
    
    // Authentication
    bearerAuth("your-token-here")
    
    // Timeout for this request
    timeout {
        requestTimeoutMillis = 30000
    }
}

URL and Parameter Functions

Functions for URL construction and parameter management.

/**
 * Configure URL using string
 * @param urlString URL string
 */
fun HttpRequestBuilder.url(urlString: String)

/**
 * Configure URL using URL object
 * @param url URL object
 */
fun HttpRequestBuilder.url(url: Url)

/**
 * Add multiple parameters from Parameters object
 * @param parameters Parameters to add
 */
fun HttpRequestBuilder.parameter(parameters: Parameters)

/**
 * Add parameter only if value is not null
 * @param key Parameter name
 * @param value Parameter value (nullable)
 */
fun HttpRequestBuilder.parameterNotNull(key: String, value: Any?)

Header Management Functions

Advanced header manipulation functions.

/**
 * Set User-Agent header
 * @param userAgent User agent string
 */
fun HttpRequestBuilder.userAgent(userAgent: String)

/**
 * Set multiple headers from a map
 * @param headers Map of header names to values
 */
fun HttpRequestBuilder.headers(headers: Map<String, String>)

/**
 * Configure headers with conditional logic
 * @param block Header configuration block
 */
fun HttpRequestBuilder.headers(block: HeadersBuilder.() -> Unit)

Usage Examples:

client.get("https://api.example.com/users") {
    // URL configuration
    url {
        parameter("page", 1)
        parameter("limit", 50)
        fragment = "results"
    }
    
    // Header management
    userAgent("MyApp/1.0")
    headers {
        if (needsAuth) {
            append("Authorization", "Bearer $token")
        }
        append("Accept-Language", "en-US,en;q=0.9")
    }
    
    // Conditional parameters
    parameterNotNull("filter", activeFilter)
}

Types

Request Types

/**
 * HTTP request representation
 */
interface HttpRequest {
    val call: HttpClientCall
    val method: HttpMethod
    val url: Url
    val content: OutgoingContent
    val headers: Headers
    val attributes: Attributes
}

/**
 * Default implementation of HttpRequest
 */
class DefaultHttpRequest(
    override val call: HttpClientCall,
    override val method: HttpMethod,
    override val url: Url,
    override val content: OutgoingContent,
    override val headers: Headers,
    override val attributes: Attributes
) : HttpRequest

/**
 * HTTP method enumeration
 */
data class HttpMethod(val value: String) {
    companion object {
        val Get: HttpMethod
        val Post: HttpMethod
        val Put: HttpMethod
        val Delete: HttpMethod
        val Head: HttpMethod
        val Options: HttpMethod
        val Patch: HttpMethod
        
        fun parse(method: String): HttpMethod
    }
}

/**
 * Request body content types
 */
sealed class OutgoingContent {
    object NoContent : OutgoingContent()
    abstract class ByteArrayContent : OutgoingContent()
    abstract class ReadChannelContent : OutgoingContent()
    abstract class WriteChannelContent : OutgoingContent()
    abstract class ProtocolUpgrade : OutgoingContent()
}

URL and Parameter Types

/**
 * URL builder for constructing URLs
 */
class URLBuilder {
    var protocol: URLProtocol
    var host: String
    var port: Int
    var user: String?
    var password: String?
    var pathSegments: MutableList<String>
    var parameters: ParametersBuilder
    var fragment: String
    var trailingQuery: Boolean
    
    fun path(vararg components: String)
    fun path(components: List<String>)
    fun build(): Url
}

/**
 * Parameters collection
 */
interface Parameters {
    val caseInsensitiveName: Boolean
    fun getAll(name: String): List<String>?
    fun names(): Set<String>
    fun isEmpty(): Boolean
    
    companion object {
        val Empty: Parameters
        
        fun build(block: ParametersBuilder.() -> Unit): Parameters
    }
}

/**
 * Parameters builder
 */
class ParametersBuilder {
    fun append(name: String, value: String)
    fun appendAll(parameters: Parameters)
    fun appendAll(parameters: StringValues)
    fun build(): Parameters
}

Install with Tessl CLI

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

docs

client-configuration.md

cookie-management.md

forms-and-uploads.md

http-caching.md

http-requests.md

index.md

plugin-system.md

response-handling.md

server-sent-events.md

websockets.md

tile.json