Ktor 3.0.1 Help

Content encoding

The Ktor client provides the ContentEncoding plugin that allows you to enable specified compression algorithms (such as gzip and deflate) and configure their settings. This plugin serves three primary purposes:

  • Sets the Accept-Encoding header with the specified quality value.

  • Optionally encodes request body.

  • Decodes content received from a server to obtain the original payload.

Add dependencies

To use ContentEncoding, you need to include the ktor-client-encoding artifact in the build script:

implementation("io.ktor:ktor-client-encoding:$ktor_version")
implementation "io.ktor:ktor-client-encoding:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-encoding-jvm</artifactId> <version>${ktor_version}</version> </dependency>

You can learn more about artifacts required by the Ktor client from Adding client dependencies.

Install ContentEncoding

To install ContentEncoding, pass it to the install function inside a client configuration block:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.compression.* //... val client = HttpClient(CIO) { install(ContentEncoding) }

Configure ContentEncoding

The example below shows how to enable the deflate and gzip encoders on the client with the specified quality values:

val client = HttpClient(CIO) { install(ContentEncoding) { deflate(1.0F) gzip(0.9F) } }

If required, you can implement the ContentEncoder interface to create a custom encoder and pass it to the customEncoder function.

Encode request body

To encode the request body, use the compress() function inside the HttpRequestBuilder block.

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.compression.* //... val client = HttpClient(CIO) { install(ContentEncoding) } client.post("/upload") { compress("gzip") setBody(someLongBody) }
Last modified: 30 April 2024