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 provides the following functionality:
Sets the
Accept-Encodingheader 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, add the ktor-client-encoding artifact to your build script:
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:
Configure ContentEncoding
Enable encoders
You can configure which encoders are supported and specify their quality values (used in the Accept-Encoding header).
The example below enables the deflate and gzip encoders with custom quality values:
If necessary, you can implement the ContentEncoder interface to create a custom encoder and register it using the customEncoder() function.
Set the mode property
By default, ContentEncoding handles response decompression only. You can use the mode property to define how the plugin operates.
The available values are:
ContentEncodingConfig.Mode.DecompressResponseDecompresses responses only. This is the default mode.
ContentEncodingConfig.Mode.CompressRequestEnables request body compression only.
ContentEncodingConfig.Mode.AllEnables both response decompression and request compression.
Encode request body
To enable request compression, set the mode property and use the compress() function inside the HttpRequestBuilder block:
In this example:
mode = ContentEncodingConfig.Mode.CompressRequestenables request compression.gzip()registers the gzip encoder.compress("gzip")applies gzip compression to this specific request.The
Content-Encodingheader is added automatically.