Client Plugin
内容编码
所需依赖项: io.ktor:ktor-client-encoding
代码示例: client-content-encoding
Ktor 客户端提供了 ContentEncoding 插件,允许你启用指定的压缩算法(例如 gzip
和 deflate
)并配置其设置。该插件主要有三个用途:
- 设置
Accept-Encoding
请求头并带上指定的质量值。 - 可选地编码请求体。
- 解码从服务器接收到的内容以获取原始载荷。
添加依赖项
要使用 ContentEncoding
,你需要在构建脚本中包含 ktor-client-encoding
artifact:
Kotlin
Groovy
XML
你可以从
添加客户端依赖项
中了解更多关于 Ktor 客户端所需 artifact 的信息。 了解如何将客户端依赖项添加到现有项目中。
安装 ContentEncoding
要安装 ContentEncoding
,请将其传递给客户端配置块内的 install
函数:
kotlin
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.compression.*
//...
val client = HttpClient(CIO) {
install(ContentEncoding)
}
配置 ContentEncoding
以下示例展示了如何在客户端上启用 deflate
和 gzip
编码器并带上指定的质量值:
kotlin
val client = HttpClient(CIO) {
install(ContentEncoding) {
deflate(1.0F)
gzip(0.9F)
}
}
如果需要,你可以实现 ContentEncoder
接口来创建自定义编码器,并将其传递给 customEncoder
函数。
编码请求体
要编码请求体,请在 HttpRequestBuilder 块中使用 compress()
函数。
kotlin
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)
}