or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-management.mdengine-system.mdform-data.mdhttp-utilities.mdindex.mdplugin-system.mdrequest-operations.mdresponse-handling.mdrouting-system.mdserver-framework.md

http-utilities.mddocs/

0

# HTTP Utilities

1

2

Core HTTP types, utilities, and extensions for working with HTTP protocols in Ktor.

3

4

## Capabilities

5

6

### HTTP Methods

7

8

Standard HTTP methods enumeration with value and semantic information.

9

10

```kotlin { .api }

11

/**

12

* HTTP methods enumeration

13

*/

14

enum class HttpMethod(val value: String) {

15

Get("GET"),

16

Post("POST"),

17

Put("PUT"),

18

Delete("DELETE"),

19

Head("HEAD"),

20

Options("OPTIONS"),

21

Patch("PATCH");

22

23

companion object {

24

/**

25

* Parse HTTP method from string

26

*/

27

fun parse(method: String): HttpMethod

28

29

/**

30

* All default HTTP methods

31

*/

32

val DefaultMethods: List<HttpMethod>

33

}

34

}

35

```

36

37

**Usage Examples:**

38

39

```kotlin

40

import io.ktor.http.*

41

42

// Using HTTP methods

43

val method = HttpMethod.Get

44

println(method.value) // "GET"

45

46

// Parsing from string

47

val parsed = HttpMethod.parse("POST") // HttpMethod.Post

48

49

// Custom methods

50

val customMethod = HttpMethod("CUSTOM")

51

```

52

53

### HTTP Status Codes

54

55

Comprehensive HTTP status code definitions with descriptions.

56

57

```kotlin { .api }

58

/**

59

* HTTP status code with value and description

60

*/

61

data class HttpStatusCode(val value: Int, val description: String) {

62

companion object {

63

// 1xx Informational

64

val Continue = HttpStatusCode(100, "Continue")

65

val SwitchingProtocols = HttpStatusCode(101, "Switching Protocols")

66

val Processing = HttpStatusCode(102, "Processing")

67

68

// 2xx Success

69

val OK = HttpStatusCode(200, "OK")

70

val Created = HttpStatusCode(201, "Created")

71

val Accepted = HttpStatusCode(202, "Accepted")

72

val NonAuthoritativeInformation = HttpStatusCode(203, "Non-Authoritative Information")

73

val NoContent = HttpStatusCode(204, "No Content")

74

val ResetContent = HttpStatusCode(205, "Reset Content")

75

val PartialContent = HttpStatusCode(206, "Partial Content")

76

77

// 3xx Redirection

78

val MultipleChoices = HttpStatusCode(300, "Multiple Choices")

79

val MovedPermanently = HttpStatusCode(301, "Moved Permanently")

80

val Found = HttpStatusCode(302, "Found")

81

val SeeOther = HttpStatusCode(303, "See Other")

82

val NotModified = HttpStatusCode(304, "Not Modified")

83

val UseProxy = HttpStatusCode(305, "Use Proxy")

84

val TemporaryRedirect = HttpStatusCode(307, "Temporary Redirect")

85

val PermanentRedirect = HttpStatusCode(308, "Permanent Redirect")

86

87

// 4xx Client Error

88

val BadRequest = HttpStatusCode(400, "Bad Request")

89

val Unauthorized = HttpStatusCode(401, "Unauthorized")

90

val PaymentRequired = HttpStatusCode(402, "Payment Required")

91

val Forbidden = HttpStatusCode(403, "Forbidden")

92

val NotFound = HttpStatusCode(404, "Not Found")

93

val MethodNotAllowed = HttpStatusCode(405, "Method Not Allowed")

94

val NotAcceptable = HttpStatusCode(406, "Not Acceptable")

95

val RequestTimeout = HttpStatusCode(408, "Request Timeout")

96

val Conflict = HttpStatusCode(409, "Conflict")

97

val Gone = HttpStatusCode(410, "Gone")

98

val UnprocessableEntity = HttpStatusCode(422, "Unprocessable Entity")

99

val TooManyRequests = HttpStatusCode(429, "Too Many Requests")

100

101

// 5xx Server Error

102

val InternalServerError = HttpStatusCode(500, "Internal Server Error")

103

val NotImplemented = HttpStatusCode(501, "Not Implemented")

104

val BadGateway = HttpStatusCode(502, "Bad Gateway")

105

val ServiceUnavailable = HttpStatusCode(503, "Service Unavailable")

106

val GatewayTimeout = HttpStatusCode(504, "Gateway Timeout")

107

val VersionNotSupported = HttpStatusCode(505, "HTTP Version Not Supported")

108

109

/**

110

* Find status code by value

111

*/

112

fun fromValue(value: Int): HttpStatusCode

113

114

/**

115

* All status codes by category

116

*/

117

val allStatusCodes: List<HttpStatusCode>

118

}

119

120

/**

121

* Check if status code is successful (2xx)

122

*/

123

val isSuccess: Boolean get() = value in 200..299

124

125

/**

126

* Check if status code is informational (1xx)

127

*/

128

val isInformational: Boolean get() = value in 100..199

129

130

/**

131

* Check if status code is redirection (3xx)

132

*/

133

val isRedirection: Boolean get() = value in 300..399

134

135

/**

136

* Check if status code is client error (4xx)

137

*/

138

val isClientError: Boolean get() = value in 400..499

139

140

/**

141

* Check if status code is server error (5xx)

142

*/

143

val isServerError: Boolean get() = value in 500..599

144

}

145

```

146

147

### Headers Interface

148

149

HTTP headers container with case-insensitive access and manipulation.

150

151

```kotlin { .api }

152

/**

153

* HTTP headers interface

154

*/

155

interface Headers : StringValues {

156

companion object {

157

/**

158

* Empty headers instance

159

*/

160

val Empty: Headers

161

162

/**

163

* Build headers from key-value pairs

164

*/

165

fun build(builder: HeadersBuilder.() -> Unit = {}): Headers

166

}

167

}

168

169

/**

170

* Mutable headers builder

171

*/

172

class HeadersBuilder : StringValuesBuilder {

173

/**

174

* Append header value

175

*/

176

fun append(name: String, value: String)

177

178

/**

179

* Set header value (replaces existing)

180

*/

181

operator fun set(name: String, value: String)

182

183

/**

184

* Remove header

185

*/

186

fun remove(name: String): Boolean

187

188

/**

189

* Build immutable headers

190

*/

191

fun build(): Headers

192

}

193

194

/**

195

* String values interface for headers and parameters

196

*/

197

interface StringValues {

198

/**

199

* Get first value for name

200

*/

201

operator fun get(name: String): String?

202

203

/**

204

* Get all values for name

205

*/

206

fun getAll(name: String): List<String>?

207

208

/**

209

* Check if name exists

210

*/

211

operator fun contains(name: String): Boolean

212

213

/**

214

* Check if empty

215

*/

216

fun isEmpty(): Boolean

217

218

/**

219

* Get all names

220

*/

221

fun names(): Set<String>

222

223

/**

224

* Get all entries

225

*/

226

fun entries(): Set<Map.Entry<String, List<String>>>

227

228

/**

229

* Iterate over entries

230

*/

231

fun forEach(action: (String, List<String>) -> Unit)

232

}

233

```

234

235

**Usage Examples:**

236

237

```kotlin

238

import io.ktor.http.*

239

240

// Build headers

241

val headers = Headers.build {

242

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

243

append("Accept", "application/json")

244

append("Authorization", "Bearer token123")

245

set("User-Agent", "Ktor Client")

246

}

247

248

// Access headers

249

val contentType = headers["Content-Type"] // "application/json"

250

val acceptHeaders = headers.getAll("Accept") // ["application/json"]

251

val hasAuth = "Authorization" in headers // true

252

253

// Iterate headers

254

headers.forEach { name, values ->

255

println("$name: ${values.joinToString(", ")}")

256

}

257

```

258

259

### Content Types

260

261

MIME type representations and content type handling.

262

263

```kotlin { .api }

264

/**

265

* Content type representation

266

*/

267

data class ContentType(

268

val contentType: String,

269

val contentSubtype: String,

270

val parameters: List<HeaderValueParam> = emptyList()

271

) {

272

companion object {

273

// Text types

274

val Text = ContentType("text", "*")

275

val Text.Plain = ContentType("text", "plain")

276

val Text.CSS = ContentType("text", "css")

277

val Text.CSV = ContentType("text", "csv")

278

val Text.Html = ContentType("text", "html")

279

val Text.JavaScript = ContentType("text", "javascript")

280

val Text.VCard = ContentType("text", "vcard")

281

val Text.Xml = ContentType("text", "xml")

282

283

// Application types

284

val Application = ContentType("application", "*")

285

val Application.Atom = ContentType("application", "atom+xml")

286

val Application.Json = ContentType("application", "json")

287

val Application.JavaScript = ContentType("application", "javascript")

288

val Application.OctetStream = ContentType("application", "octet-stream")

289

val Application.FontWoff = ContentType("application", "font-woff")

290

val Application.Rss = ContentType("application", "rss+xml")

291

val Application.Xml = ContentType("application", "xml")

292

val Application.Zip = ContentType("application", "zip")

293

val Application.GZip = ContentType("application", "gzip")

294

val Application.FormUrlEncoded = ContentType("application", "x-www-form-urlencoded")

295

val Application.Pdf = ContentType("application", "pdf")

296

297

// Multipart types

298

val MultiPart = ContentType("multipart", "*")

299

val MultiPart.Mixed = ContentType("multipart", "mixed")

300

val MultiPart.Alternative = ContentType("multipart", "alternative")

301

val MultiPart.Related = ContentType("multipart", "related")

302

val MultiPart.FormData = ContentType("multipart", "form-data")

303

val MultiPart.Signed = ContentType("multipart", "signed")

304

val MultiPart.Encrypted = ContentType("multipart", "encrypted")

305

val MultiPart.ByteRanges = ContentType("multipart", "byteranges")

306

307

// Image types

308

val Image = ContentType("image", "*")

309

val Image.JPEG = ContentType("image", "jpeg")

310

val Image.PNG = ContentType("image", "png")

311

val Image.GIF = ContentType("image", "gif")

312

val Image.SVG = ContentType("image", "svg+xml")

313

314

// Audio types

315

val Audio = ContentType("audio", "*")

316

val Audio.MP4 = ContentType("audio", "mp4")

317

val Audio.MPEG = ContentType("audio", "mpeg")

318

val Audio.OGG = ContentType("audio", "ogg")

319

320

// Video types

321

val Video = ContentType("video", "*")

322

val Video.MPEG = ContentType("video", "mpeg")

323

val Video.MP4 = ContentType("video", "mp4")

324

val Video.OGG = ContentType("video", "ogg")

325

val Video.QuickTime = ContentType("video", "quicktime")

326

327

/**

328

* Parse content type from string

329

*/

330

fun parse(value: String): ContentType

331

}

332

333

/**

334

* Content type with charset parameter

335

*/

336

fun withCharset(charset: Charset): ContentType

337

338

/**

339

* Content type with parameter

340

*/

341

fun withParameter(name: String, value: String): ContentType

342

343

/**

344

* Match against another content type

345

*/

346

fun match(pattern: ContentType): Boolean

347

348

/**

349

* String representation

350

*/

351

override fun toString(): String

352

}

353

```

354

355

### URL Building

356

357

URL construction and manipulation utilities.

358

359

```kotlin { .api }

360

/**

361

* URL builder for constructing URLs programmatically

362

*/

363

class URLBuilder(

364

var protocol: URLProtocol = URLProtocol.HTTP,

365

var host: String = "localhost",

366

var port: Int = DEFAULT_PORT,

367

var user: String? = null,

368

var password: String? = null,

369

var pathSegments: MutableList<String> = mutableListOf(),

370

var parameters: ParametersBuilder = ParametersBuilder(),

371

var fragment: String = "",

372

var trailingQuery: Boolean = false

373

) {

374

/**

375

* Build URL string

376

*/

377

fun buildString(): String

378

379

/**

380

* Build Url object

381

*/

382

fun build(): Url

383

384

/**

385

* Clone this builder

386

*/

387

fun clone(): URLBuilder

388

}

389

390

/**

391

* URL protocol enumeration

392

*/

393

enum class URLProtocol(val name: String, val defaultPort: Int) {

394

HTTP("http", 80),

395

HTTPS("https", 443),

396

WS("ws", 80),

397

WSS("wss", 443),

398

FILE("file", 0),

399

SOCKS("socks", 1080);

400

401

companion object {

402

/**

403

* Create protocol from name

404

*/

405

fun createOrDefault(name: String): URLProtocol

406

}

407

}

408

409

/**

410

* Immutable URL representation

411

*/

412

data class Url(

413

val protocol: URLProtocol,

414

val host: String,

415

val port: Int,

416

val user: String?,

417

val password: String?,

418

val pathSegments: List<String>,

419

val parameters: Parameters,

420

val fragment: String,

421

val trailingQuery: Boolean

422

) {

423

companion object {

424

/**

425

* Parse URL from string

426

*/

427

fun parse(urlString: String): Url

428

}

429

430

/**

431

* Convert to string

432

*/

433

override fun toString(): String

434

}

435

```

436

437

**Usage Examples:**

438

439

```kotlin

440

import io.ktor.http.*

441

442

// Build URL programmatically

443

val url = URLBuilder().apply {

444

protocol = URLProtocol.HTTPS

445

host = "api.example.com"

446

port = 443

447

pathSegments.addAll(listOf("v1", "users"))

448

parameters.append("page", "1")

449

parameters.append("limit", "10")

450

}.buildString()

451

// Result: "https://api.example.com/v1/users?page=1&limit=10"

452

453

// Parse existing URL

454

val parsed = Url.parse("https://example.com:8080/path?query=value#section")

455

println(parsed.host) // "example.com"

456

println(parsed.port) // 8080

457

println(parsed.pathSegments) // ["path"]

458

```

459

460

### Parameters Interface

461

462

URL parameters and form data handling.

463

464

```kotlin { .api }

465

/**

466

* Parameters interface for URL query parameters and form data

467

*/

468

interface Parameters : StringValues {

469

companion object {

470

/**

471

* Empty parameters instance

472

*/

473

val Empty: Parameters

474

475

/**

476

* Build parameters from key-value pairs

477

*/

478

fun build(builder: ParametersBuilder.() -> Unit = {}): Parameters

479

}

480

}

481

482

/**

483

* Mutable parameters builder

484

*/

485

class ParametersBuilder : StringValuesBuilder {

486

/**

487

* Append parameter value

488

*/

489

fun append(name: String, value: String)

490

491

/**

492

* Set parameter value (replaces existing)

493

*/

494

operator fun set(name: String, value: String)

495

496

/**

497

* Remove parameter

498

*/

499

fun remove(name: String): Boolean

500

501

/**

502

* Append all values from another Parameters

503

*/

504

fun appendAll(other: Parameters)

505

506

/**

507

* Build immutable parameters

508

*/

509

fun build(): Parameters

510

}

511

```

512

513

### HTTP Authentication

514

515

HTTP authentication utilities and challenges.

516

517

```kotlin { .api }

518

/**

519

* HTTP authentication challenge

520

*/

521

sealed class HttpAuthHeader {

522

/**

523

* Basic authentication challenge

524

*/

525

data class Single(val authScheme: String, val parameter: String) : HttpAuthHeader()

526

527

/**

528

* Parameterized authentication challenge

529

*/

530

data class Parameterized(

531

val authScheme: String,

532

val parameters: List<HeaderValueParam>

533

) : HttpAuthHeader()

534

535

companion object {

536

/**

537

* Parse authentication header

538

*/

539

fun parse(headerValue: String): HttpAuthHeader?

540

}

541

}

542

543

/**

544

* Header value parameter

545

*/

546

data class HeaderValueParam(val name: String, val value: String) {

547

/**

548

* Parameter with escaped value

549

*/

550

val escapeIfNeeded: String

551

}

552

```