Comprehensive request building DSL with support for all HTTP methods, headers, query parameters, and body content. The request building system provides a fluent API for constructing HTTP requests with type safety and flexible configuration options.
Primary functions for making HTTP requests with various configuration options.
/**
* Make an HTTP request using a builder DSL
*/
suspend fun HttpClient.request(
builder: HttpRequestBuilder = HttpRequestBuilder()
): HttpResponse
/**
* Make an HTTP request using a configuration block
*/
suspend fun HttpClient.request(
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make an HTTP request to a specific URL string
*/
suspend fun HttpClient.request(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make an HTTP request to a specific URL
*/
suspend fun HttpClient.request(
url: Url,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponseConvenience functions for specific HTTP methods.
/**
* Make a GET request
*/
suspend fun HttpClient.get(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
suspend fun HttpClient.get(
url: Url,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
suspend fun HttpClient.get(
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make a POST request
*/
suspend fun HttpClient.post(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
suspend fun HttpClient.post(
url: Url,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
suspend fun HttpClient.post(
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make a PUT request
*/
suspend fun HttpClient.put(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make a DELETE request
*/
suspend fun HttpClient.delete(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make a PATCH request
*/
suspend fun HttpClient.patch(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make an OPTIONS request
*/
suspend fun HttpClient.options(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponse
/**
* Make a HEAD request
*/
suspend fun HttpClient.head(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpResponseFunctions that return HttpStatement for deferred execution and streaming support.
/**
* Prepare an HTTP request for deferred execution
*/
fun HttpClient.prepareRequest(
builder: HttpRequestBuilder = HttpRequestBuilder()
): HttpStatement
fun HttpClient.prepareRequest(
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
fun HttpClient.prepareRequest(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
/**
* Prepare method-specific requests
*/
fun HttpClient.prepareGet(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
fun HttpClient.preparePost(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
fun HttpClient.preparePut(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
fun HttpClient.prepareDelete(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
fun HttpClient.preparePatch(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
fun HttpClient.prepareOptions(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatement
fun HttpClient.prepareHead(
urlString: String,
block: HttpRequestBuilder.() -> Unit = {}
): HttpStatementMutable builder class for constructing HTTP requests with comprehensive configuration options.
/**
* Builder for constructing HTTP requests
*/
class HttpRequestBuilder {
/** HTTP method (default: GET) */
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
/** Type information for the request body */
var bodyType: TypeInfo?
/** Execution context for the request */
var executionContext: Job
/** Request attributes container */
val attributes: Attributes
/**
* Build immutable HttpRequestData from this builder
*/
fun build(): HttpRequestData
/**
* Configure the request URL
*/
fun url(block: URLBuilder.() -> Unit)
/**
* Configure request attributes
*/
fun setAttributes(block: Attributes.() -> Unit)
/**
* Set the request body with type information
*/
fun setBody(body: Any?, bodyType: TypeInfo)
/**
* Set the request body with reified type information
*/
inline fun <reified T> setBody(body: T)
/**
* Copy configuration from another builder
*/
fun takeFrom(builder: HttpRequestBuilder): HttpRequestBuilder
/**
* Set an engine capability
*/
fun <T : Any> setCapability(
key: HttpClientEngineCapability<T>,
capability: T
)
/**
* Get an engine capability
*/
fun <T : Any> getCapabilityOrNull(
key: HttpClientEngineCapability<T>
): T?
}URL construction and parameter handling within requests.
/**
* URL builder for constructing request URLs
*/
class URLBuilder {
var protocol: URLProtocol
var host: String
var port: Int
var encodedPath: String
val parameters: ParametersBuilder
val fragment: String
var user: String?
var password: String?
/**
* Set a query parameter
*/
fun parameter(key: String, value: Any?)
/**
* Set multiple query parameters
*/
fun parameters(block: ParametersBuilder.() -> Unit)
/**
* Build the final URL
*/
fun build(): Url
}
/**
* Builder for URL parameters
*/
class ParametersBuilder {
/**
* Append a parameter value
*/
fun append(name: String, value: String)
/**
* Append all values for a parameter
*/
fun appendAll(name: String, values: Iterable<String>)
/**
* Set a parameter value (replaces existing)
*/
fun set(name: String, value: String)
/**
* Remove a parameter
*/
fun remove(name: String)
/**
* Clear all parameters
*/
fun clear()
/**
* Build immutable Parameters
*/
fun build(): Parameters
}Header management and construction for HTTP requests.
/**
* Builder for HTTP headers
*/
class HeadersBuilder {
/**
* Append a header value
*/
fun append(name: String, value: String)
/**
* Append all values for a header
*/
fun appendAll(name: String, values: Iterable<String>)
/**
* Set a header value (replaces existing)
*/
fun set(name: String, value: String)
/**
* Remove a header
*/
fun remove(name: String)
/**
* Clear all headers
*/
fun clear()
/**
* Build immutable Headers
*/
fun build(): Headers
}
/**
* Convenience functions for common headers
*/
fun HttpRequestBuilder.contentType(contentType: ContentType)
fun HttpRequestBuilder.accept(contentType: ContentType)
fun HttpRequestBuilder.userAgent(userAgent: String)
fun HttpRequestBuilder.bearerAuth(token: String)
fun HttpRequestBuilder.basicAuth(username: String, password: String)Usage Examples:
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
val client = HttpClient()
// Basic GET request
val response = client.get("https://api.example.com/users")
// GET with query parameters
val searchResponse = client.get("https://api.example.com/search") {
url {
parameter("q", "kotlin")
parameter("limit", 10)
parameter("offset", 0)
}
}
// POST with JSON body
val createResponse = client.post("https://api.example.com/users") {
contentType(ContentType.Application.Json)
setBody("""{"name": "John", "email": "john@example.com"}""")
}
// PUT with headers
val updateResponse = client.put("https://api.example.com/users/123") {
headers {
append("Authorization", "Bearer $token")
append("X-Custom-Header", "custom-value")
}
contentType(ContentType.Application.Json)
setBody(userUpdateData)
}
// Complex request with multiple configurations
val complexResponse = client.request {
method = HttpMethod.Patch
url {
protocol = URLProtocol.HTTPS
host = "api.example.com"
encodedPath = "/users/123"
parameter("include", "profile")
}
headers {
append("Authorization", "Bearer $token")
append("Content-Type", "application/json")
append("Accept", "application/json")
}
setBody(patchData)
// Set request attributes
setAttributes {
put(AttributeKey("request-id"), "req-123")
}
}
// Using prepared requests for streaming
val statement = client.prepareGet("https://api.example.com/large-data")
statement.execute { response ->
val channel = response.bodyAsChannel()
// Process streaming response
while (!channel.isClosedForRead) {
val chunk = channel.readBuffer()
// Process chunk
}
}
client.close()Request-specific timeout configuration.
/**
* Configure timeouts for a specific request
*/
fun HttpRequestBuilder.timeout(block: HttpTimeoutConfig.() -> Unit)
class HttpTimeoutConfig {
/** Request timeout in milliseconds */
var requestTimeoutMillis: Long?
/** Connection timeout in milliseconds */
var connectTimeoutMillis: Long?
/** Socket timeout in milliseconds */
var socketTimeoutMillis: Long?
}Immutable data classes representing built request data.
/**
* Immutable HTTP request data
*/
data class HttpRequestData(
val url: Url,
val method: HttpMethod,
val headers: Headers,
val body: OutgoingContent,
val executionContext: Job,
val attributes: Attributes
) {
/**
* Get an engine capability if available
*/
fun <T : Any> getCapabilityOrNull(
key: HttpClientEngineCapability<T>
): T?
}
/**
* HTTP method enumeration
*/
enum class HttpMethod(val value: String) {
Get("GET"),
Post("POST"),
Put("PUT"),
Delete("DELETE"),
Head("HEAD"),
Options("OPTIONS"),
Patch("PATCH"),
Trace("TRACE"),
Connect("CONNECT");
companion object {
fun parse(method: String): HttpMethod
}
}