or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

built-in-plugins.mdengine-configuration.mdform-data-content.mdhttp-client.mdindex.mdplugin-system.mdrequest-building.mdresponse-handling.md

index.mddocs/

0

# Ktor Client Core

1

2

Ktor Client Core is a multiplatform asynchronous HTTP client library that provides comprehensive HTTP client functionality for Kotlin applications. It offers coroutine-based HTTP operations, request/response handling, authentication, content negotiation, and WebSocket support with multiplatform compatibility across JVM, Android, iOS, JavaScript, and native platforms including macOS ARM64.

3

4

## Package Information

5

6

- **Package Name**: ktor-client-core-macosarm64

7

- **Package Type**: maven

8

- **Language**: Kotlin

9

- **Installation**: Implementation dependency in Gradle: `implementation("io.ktor:ktor-client-core:3.2.0")`

10

11

## Core Imports

12

13

```kotlin

14

import io.ktor.client.*

15

import io.ktor.client.request.*

16

import io.ktor.client.statement.*

17

import io.ktor.client.call.*

18

import io.ktor.client.engine.*

19

import io.ktor.client.plugins.*

20

```

21

22

## Basic Usage

23

24

```kotlin

25

import io.ktor.client.*

26

import io.ktor.client.request.*

27

import io.ktor.client.statement.*

28

29

// Create a client

30

val client = HttpClient()

31

32

try {

33

// Make a GET request

34

val response: HttpResponse = client.get("https://ktor.io/")

35

val content: String = response.bodyAsText()

36

println(content)

37

38

// Make a POST request with JSON

39

val postResponse = client.post("https://api.example.com/data") {

40

setBody("""{"name": "value"}""")

41

headers {

42

append("Content-Type", "application/json")

43

}

44

}

45

} finally {

46

// Always close the client

47

client.close()

48

}

49

```

50

51

## Architecture

52

53

Ktor Client Core is built around several key architectural components:

54

55

- **HttpClient**: Main client class providing HTTP operations with configurable engines and plugins

56

- **Request Pipeline**: Processing chain for outgoing HTTP requests with interceptor support

57

- **Response Pipeline**: Processing chain for incoming HTTP responses with transformation support

58

- **Engine Abstraction**: Platform-specific HTTP implementations (CIO, Apache, OkHttp, etc.)

59

- **Plugin System**: Extensible middleware for authentication, logging, content negotiation, and more

60

- **Multiplatform Support**: Consistent API across JVM, Android, iOS, JavaScript, and native platforms

61

62

## Capabilities

63

64

### HTTP Client Operations

65

66

Core HTTP client functionality for making requests, handling responses, and managing client lifecycle. Provides coroutine-based API with full multiplatform support.

67

68

```kotlin { .api }

69

class HttpClient(

70

engine: HttpClientEngine,

71

userConfig: HttpClientConfig<out HttpClientEngineConfig> = HttpClientConfig()

72

) : CoroutineScope, Closeable {

73

val engine: HttpClientEngine

74

val requestPipeline: HttpRequestPipeline

75

val responsePipeline: HttpResponsePipeline

76

val sendPipeline: HttpSendPipeline

77

val receivePipeline: HttpReceivePipeline

78

val attributes: Attributes

79

val engineConfig: HttpClientEngineConfig

80

val monitor: Events

81

82

fun isSupported(capability: HttpClientEngineCapability<*>): Boolean

83

fun config(block: HttpClientConfig<*>.() -> Unit): HttpClient

84

override fun close()

85

}

86

87

expect fun HttpClient(

88

block: HttpClientConfig<*>.() -> Unit = {}

89

): HttpClient

90

```

91

92

[HTTP Client Operations](./http-client.md)

93

94

### Request Building and Configuration

95

96

Request building DSL for constructing HTTP requests with headers, parameters, body content, and various configuration options.

97

98

```kotlin { .api }

99

class HttpRequestBuilder {

100

var method: HttpMethod

101

val url: URLBuilder

102

val headers: HeadersBuilder

103

var body: Any

104

val attributes: Attributes

105

var executionContext: Job?

106

107

fun header(key: String, value: String)

108

fun headers(block: HeadersBuilder.() -> Unit)

109

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

110

fun accept(contentType: ContentType)

111

fun contentType(contentType: ContentType)

112

fun userAgent(agent: String)

113

fun basicAuth(username: String, password: String)

114

fun bearerAuth(token: String)

115

fun timeout(block: HttpTimeoutCapabilityConfiguration.() -> Unit)

116

fun build(): HttpRequestData

117

}

118

119

suspend fun HttpClient.request(block: HttpRequestBuilder.() -> Unit): HttpResponse

120

suspend fun HttpClient.get(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

121

suspend fun HttpClient.post(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

122

suspend fun HttpClient.put(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

123

suspend fun HttpClient.delete(urlString: block: HttpRequestBuilder.() -> Unit = {}): HttpResponse

124

```

125

126

[Request Building](./request-building.md)

127

128

### Response Handling and Processing

129

130

Response processing capabilities for extracting data from HTTP responses, handling different content types, and streaming response data.

131

132

```kotlin { .api }

133

interface HttpResponse {

134

val call: HttpClientCall

135

val status: HttpStatusCode

136

val version: HttpProtocolVersion

137

val requestTime: GMTDate

138

val responseTime: GMTDate

139

val headers: Headers

140

override val coroutineContext: CoroutineContext

141

}

142

143

class HttpStatement(

144

private val builder: HttpRequestBuilder,

145

private val client: HttpClient

146

) {

147

suspend fun execute(block: suspend (response: HttpResponse) -> T): T

148

suspend inline fun <reified T> body(): T

149

suspend fun bodyAsText(fallbackCharset: Charset = Charsets.UTF_8): String

150

suspend fun bodyAsChannel(): ByteReadChannel

151

suspend fun bodyAsBytes(): ByteArray

152

}

153

154

suspend inline fun <reified T> HttpResponse.body(): T

155

suspend fun HttpResponse.bodyAsText(fallbackCharset: Charset = Charsets.UTF_8): String

156

suspend fun HttpResponse.bodyAsChannel(): ByteReadChannel

157

suspend fun HttpResponse.bodyAsBytes(): ByteArray

158

```

159

160

[Response Handling](./response-handling.md)

161

162

### Engine Configuration and Management

163

164

HTTP engine abstraction providing platform-specific implementations and configuration options for connection management, timeouts, and networking behavior.

165

166

```kotlin { .api }

167

interface HttpClientEngine : CoroutineScope, Closeable {

168

val config: HttpClientEngineConfig

169

val dispatcher: CoroutineDispatcher

170

val supportedCapabilities: Set<HttpClientEngineCapability<*>>

171

172

suspend fun execute(data: HttpRequestData): HttpResponseData

173

fun install(client: HttpClient)

174

}

175

176

open class HttpClientEngineConfig {

177

var dispatcher: CoroutineDispatcher?

178

var pipelining: Boolean

179

var proxy: ProxyConfig?

180

var localAddress: SocketAddress?

181

182

fun proxy(url: String)

183

}

184

185

interface HttpClientEngineFactory<out T : HttpClientEngineConfig> {

186

fun create(block: T.() -> Unit = {}): HttpClientEngine

187

}

188

```

189

190

[Engine Configuration](./engine-configuration.md)

191

192

### Plugin System and Extensibility

193

194

Plugin framework for extending client functionality with authentication, logging, content negotiation, caching, and custom middleware.

195

196

```kotlin { .api }

197

interface HttpClientPlugin<TConfig : Any, TPlugin : Any> {

198

val key: AttributeKey<TPlugin>

199

fun prepare(block: TConfig.() -> Unit): TPlugin

200

fun install(plugin: TPlugin, scope: HttpClient)

201

}

202

203

class ClientPluginBuilder<TConfig : Any>(

204

private val name: String

205

) {

206

fun on(event: ClientHook<*>, block: suspend ClientHookHandler<*>.() -> Unit)

207

fun onRequest(block: suspend OnRequestContext.() -> Unit)

208

fun onResponse(block: suspend OnResponseContext.() -> Unit)

209

fun transformRequestBody(block: suspend TransformRequestBodyContext.() -> Unit)

210

fun transformResponseBody(block: suspend TransformResponseBodyContext.() -> Unit)

211

}

212

213

fun <TConfig : Any> createClientPlugin(

214

name: String,

215

createConfiguration: () -> TConfig,

216

body: ClientPluginBuilder<TConfig>.() -> Unit

217

): HttpClientPlugin<TConfig, *>

218

```

219

220

[Plugin System](./plugin-system.md)

221

222

### Built-in Plugins and Features

223

224

Comprehensive set of built-in plugins providing essential HTTP client features including authentication, cookies, redirects, timeouts, content negotiation, and WebSocket support.

225

226

```kotlin { .api }

227

object HttpRequestLifecycle : HttpClientPlugin<Unit, Unit>

228

object BodyProgress : HttpClientPlugin<Unit, Unit>

229

object SaveBody : HttpClientPlugin<Unit, Unit>

230

object HttpSend : HttpClientPlugin<Unit, Unit>

231

object HttpPlainText : HttpClientPlugin<Unit, Unit>

232

object HttpCallValidator : HttpClientPlugin<Unit, Unit>

233

object HttpRedirect : HttpClientPlugin<Unit, Unit>

234

object HttpCookies : HttpClientPlugin<HttpCookiesConfig, HttpCookies>

235

object HttpCache : HttpClientPlugin<Unit, Unit>

236

object HttpTimeout : HttpClientPlugin<HttpTimeoutCapabilityConfiguration, Unit>

237

object Auth : HttpClientPlugin<AuthConfig, Auth>

238

object WebSockets : HttpClientPlugin<WebSocketConfig, Unit>

239

object SSE : HttpClientPlugin<Unit, Unit>

240

```

241

242

[Built-in Plugins](./built-in-plugins.md)

243

244

### Form Data and Content Handling

245

246

Content handling for form data, multipart uploads, file uploads, and various content types with proper encoding and streaming support.

247

248

```kotlin { .api }

249

class FormDataContent(formData: Parameters) : OutgoingContent.ByteArrayContent()

250

class MultiPartFormDataContent(

251

private val formData: List<PartData>,

252

override val contentType: ContentType = ContentType.MultiPart.FormData.withParameter("boundary", boundary),

253

override val contentLength: Long? = null

254

) : OutgoingContent.WriteChannelContent()

255

256

class ParametersBuilder(size: Int = 8) : StringValuesBuilder {

257

fun append(name: String, value: String)

258

fun appendAll(stringValues: StringValues)

259

fun appendAll(name: String, values: Iterable<String>)

260

fun appendMissing(stringValues: StringValues)

261

fun appendMissing(name: String, values: Iterable<String>)

262

fun build(): Parameters

263

}

264

265

suspend fun HttpClient.submitForm(

266

url: String,

267

formParameters: Parameters = Parameters.Empty,

268

encodeInQuery: Boolean = false,

269

block: HttpRequestBuilder.() -> Unit = {}

270

): HttpResponse

271

272

suspend fun HttpClient.submitFormWithBinaryData(

273

url: String,

274

formData: List<PartData>,

275

block: HttpRequestBuilder.() -> Unit = {}

276

): HttpResponse

277

```

278

279

[Form Data and Content](./form-data-content.md)

280

281

## Types

282

283

### Core Types

284

285

```kotlin { .api }

286

class HttpClientCall(

287

val client: HttpClient,

288

val request: HttpRequest,

289

val response: HttpResponse,

290

val attributes: Attributes

291

) {

292

suspend inline fun <reified T> body(): T

293

suspend inline fun <reified T> bodyNullable(): T?

294

fun save(): SavedHttpCall

295

}

296

297

interface HttpRequest {

298

val call: HttpClientCall

299

val method: HttpMethod

300

val url: Url

301

val attributes: Attributes

302

val headers: Headers

303

val body: OutgoingContent

304

}

305

306

class HttpRequestPipeline : Pipeline<Any, HttpRequestBuilder>

307

class HttpResponsePipeline : Pipeline<HttpResponseContainer, HttpClientCall>

308

class HttpSendPipeline : Pipeline<Any, HttpClientCall>

309

class HttpReceivePipeline : Pipeline<HttpResponseContainer, HttpClientCall>

310

```

311

312

### Configuration Types

313

314

```kotlin { .api }

315

class HttpClientConfig<T : HttpClientEngineConfig> {

316

var engine: T?

317

var developmentMode: Boolean

318

var expectSuccess: Boolean

319

var useDefaultTransformers: Boolean

320

var followRedirects: Boolean

321

322

fun engine(block: T.() -> Unit)

323

fun install(plugin: HttpClientPlugin<*, *>)

324

fun install(key: String, block: HttpClientConfig<HttpClientEngineConfig>.() -> Unit)

325

operator fun plus(other: HttpClientConfig<out HttpClientEngineConfig>): HttpClientConfig<T>

326

fun clone(): HttpClientConfig<T>

327

}

328

329

class ProxyConfig(

330

val type: ProxyType,

331

val address: SocketAddress

332

)

333

334

enum class ProxyType { HTTP, SOCKS }

335

```

336

337

### Exception Types

338

339

```kotlin { .api }

340

class ClientEngineClosedException(cause: Throwable? = null) : IllegalStateException("Client engine is already closed.", cause)

341

class DoubleReceiveException(call: HttpClientCall) : IllegalStateException("Response already received: $call")

342

class NoTransformationFoundException(from: KType, to: KType) : UnsupportedOperationException("No transformation found: $from -> $to")

343

class HttpRequestTimeoutException(url: String, timeoutMillis: Long) : IOException("Request timeout has expired [url=$url, timeout_ms=$timeoutMillis]")

344

class ConnectTimeoutException(message: String, cause: Throwable? = null) : IOException(message, cause)

345

class SocketTimeoutException(message: String, cause: Throwable? = null) : IOException(message, cause)

346

```