自定义客户端插件
代码示例: client-custom-plugin
从 v2.2.0 开始,Ktor 提供了一套用于创建自定义客户端插件的新 API。通常,该 API 不需要了解流水线(pipeline)、阶段(phase)等 Ktor 内部概念。 相反,你可以使用一组处理程序(例如 onRequest、onResponse 等)来访问处理请求和响应的不同阶段。
创建并安装你的第一个插件
在本节中,我们将演示如何创建并安装你的第一个插件,该插件会向每个请求添加自定义标头:
要创建插件,请调用 createClientPlugin 函数并将插件名称作为实参传递:
kotlinpackage com.example.plugins import io.ktor.client.plugins.api.* val CustomHeaderPlugin = createClientPlugin("CustomHeaderPlugin") { // 配置插件... }该函数返回将用于安装插件的
ClientPlugin实例。要向每个请求追加自定义标头,可以使用
onRequest处理程序,它提供了对请求参数的访问:kotlinpackage com.example.plugins import io.ktor.client.plugins.api.* val CustomHeaderPlugin = createClientPlugin("CustomHeaderPlugin") { onRequest { request, _ -> request.headers.append("X-Custom-Header", "Default value") } }要安装插件,请将创建的
ClientPlugin实例传递给客户端配置块内的install函数:kotlinimport com.example.plugins.* val client = HttpClient(CIO) { install(CustomHeaderPlugin) }
你可以在此处找到完整示例:CustomHeader.kt。 在接下来的几节中,我们将介绍如何提供插件配置以及处理请求和响应。
提供插件配置
上一节演示了如何创建一个向每个响应追加预定义自定义标头的插件。让我们让这个插件更加实用,并提供用于传递任意自定义标头名称和值的配置:
首先,你需要定义一个配置类:
kotlinclass CustomHeaderPluginConfig { var headerName: String = "X-Custom-Header" var headerValue: String = "Default value" }要在插件中使用此配置,请将配置类引用传递给
createClientPlugin:kotlinimport io.ktor.client.plugins.api.* val CustomHeaderConfigurablePlugin = createClientPlugin("CustomHeaderConfigurablePlugin", ::CustomHeaderPluginConfig) { val headerName = pluginConfig.headerName val headerValue = pluginConfig.headerValue onRequest { request, _ -> request.headers.append(headerName, headerValue) } }鉴于插件配置字段是可变的,建议将其保存在局部变量中。
最后,你可以按如下方式安装并配置插件:
kotlinval client = HttpClient(CIO) { install(CustomHeaderConfigurablePlugin) { headerName = "X-Custom-Header" headerValue = "Hello, world!" } }
你可以在此处找到完整示例:CustomHeaderConfigurable.kt。
处理请求和响应
自定义插件通过一组专用处理程序提供对处理请求和响应的不同阶段的访问,例如:
onRequest和onResponse分别允许你处理请求和响应。transformRequestBody和transformResponseBody可用于对请求体和响应体应用必要的转换。
还有一个 on(...) 处理程序,允许你调用可能对处理调用的其他阶段有用的特定钩子。 下表按执行顺序列出了所有处理程序:
| 处理程序 | 说明 |
onRequest | 针对每个 HTTP 请求了解如何发起请求并指定各种请求参数:请求 URL、HTTP 方法、标头以及请求体。执行此处理程序,并允许对其进行修改。 示例:自定义标头 |
transformRequestBody | 允许你转换请求体。 在此处理程序中,你需要将请求体序列化为 OutgoingContent (例如 示例:数据转换 |
onResponse | 针对每个传入的 HTTP 响应了解如何发起请求并指定各种请求参数:请求 URL、HTTP 方法、标头以及请求体。执行此处理程序,并允许你以各种方式对其进行检查:记录响应日志、保存 Cookie 等。 |
transformResponseBody | 允许你转换响应体。 每次调用 示例:数据转换 |
onClose | 允许你清理此插件分配的资源。 当客户端被关闭时调用此处理程序。 |
| 处理程序 | 说明 |
on(SetupRequest) | SetupRequest 钩子在请求处理中最先执行。 |
onRequest | 针对每个 HTTP 请求了解如何发起请求并指定各种请求参数:请求 URL、HTTP 方法、标头以及请求体。执行此处理程序,并允许对其进行修改。 示例:自定义标头 |
transformRequestBody | 允许你转换请求体。 在此处理程序中,你需要将请求体序列化为 OutgoingContent (例如 示例:数据转换 |
on(Send) |
示例:身份验证 |
on(SendingRequest) |
console |
onResponse | 针对每个传入的 HTTP 响应了解如何发起请求并指定各种请求参数:请求 URL、HTTP 方法、标头以及请求体。执行此处理程序,并允许你以各种方式对其进行检查:记录响应日志、保存 Cookie 等。 |
transformResponseBody | 允许你转换响应体。 每次调用 示例:数据转换 |
onClose | 允许你清理此插件分配的资源。 当客户端被关闭时调用此处理程序。 |
共享调用状态
自定义插件允许你共享与调用相关的任何值,以便你可以在处理该调用的任何处理程序内部访问此值。 该值作为具有唯一键的特性存储在 call.attributes 集合中。 以下示例演示了如何使用特性来计算发送请求与接收响应之间的时间:
import io.ktor.client.plugins.api.*
import io.ktor.util.*
val ResponseTimePlugin = createClientPlugin("ResponseTimePlugin") {
val onCallTimeKey = AttributeKey<Long>("onCallTimeKey")
on(SendingRequest) { request, content ->
val onCallTime = System.currentTimeMillis()
request.attributes.put(onCallTimeKey, onCallTime)
}
onResponse { response ->
val onCallTime = response.call.attributes[onCallTimeKey]
val onCallReceiveTime = System.currentTimeMillis()
println("Read response delay (ms): ${onCallReceiveTime - onCallTime}")
}
}你可以在此处找到完整示例:ResponseTime.kt。
访问客户端配置
你可以使用 client 属性访问客户端配置,该属性返回 HttpClient 实例。 以下示例演示了如何获取客户端使用的代理地址:
import io.ktor.client.plugins.api.*
val SimplePlugin = createClientPlugin("SimplePlugin") {
val proxyAddress = client.engineConfig.proxy?.address()
println("Proxy address: $proxyAddress")
}示例
以下代码示例演示了自定义插件的几个范例。 你可以在此处找到生成的完整项目:client-custom-plugin。
自定义标头
演示如何创建一个向每个请求添加自定义标头的插件:
package com.example.plugins
import io.ktor.client.plugins.api.*
val CustomHeaderConfigurablePlugin = createClientPlugin("CustomHeaderConfigurablePlugin", ::CustomHeaderPluginConfig) {
val headerName = pluginConfig.headerName
val headerValue = pluginConfig.headerValue
onRequest { request, _ ->
request.headers.append(headerName, headerValue)
}
}
class CustomHeaderPluginConfig {
var headerName: String = "X-Custom-Header"
var headerValue: String = "Default value"
}记录标头
演示如何创建一个记录请求和响应标头的插件:
package com.example.plugins
import io.ktor.client.plugins.api.*
val LoggingHeadersPlugin = createClientPlugin("LoggingHeadersPlugin") {
on(SendingRequest) { request, content ->
println("Request headers:")
request.headers.entries().forEach { entry ->
printHeader(entry)
}
}
onResponse { response ->
println("Response headers:")
response.headers.entries().forEach { entry ->
printHeader(entry)
}
}
}
private fun printHeader(entry: Map.Entry<String, List<String>>) {
var headerString = entry.key + ": "
entry.value.forEach { headerValue ->
headerString += "${headerValue};"
}
println("-> $headerString")
}响应时间
演示如何创建一个测量发送请求与接收响应之间时间的插件:
package com.example.plugins
import io.ktor.client.plugins.api.*
import io.ktor.util.*
val ResponseTimePlugin = createClientPlugin("ResponseTimePlugin") {
val onCallTimeKey = AttributeKey<Long>("onCallTimeKey")
on(SendingRequest) { request, content ->
val onCallTime = System.currentTimeMillis()
request.attributes.put(onCallTimeKey, onCallTime)
}
onResponse { response ->
val onCallTime = response.call.attributes[onCallTimeKey]
val onCallReceiveTime = System.currentTimeMillis()
println("Read response delay (ms): ${onCallReceiveTime - onCallTime}")
}
}数据转换
演示如何使用 transformRequestBody 和 transformResponseBody 钩子转换请求体和响应体:
package com.example.plugins
import com.example.model.*
import io.ktor.client.plugins.api.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.utils.io.*
val DataTransformationPlugin = createClientPlugin("DataTransformationPlugin") {
transformRequestBody { request, content, bodyType ->
if (bodyType?.type == User::class) {
val user = content as User
TextContent(text="${user.name};${user.age}", contentType = ContentType.Text.Plain)
} else {
null
}
}
transformResponseBody { response, content, requestedType ->
if (requestedType.type == User::class) {
val receivedContent = content.readLine()!!.split(";")
User(receivedContent[0], receivedContent[1].toInt())
} else {
content
}
}
}package com.example
import com.example.model.*
import com.example.plugins.*
import com.example.server.*
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.*
fun main() {
startServer()
runBlocking {
val client = HttpClient(CIO) {
install(DataTransformationPlugin)
}
val bodyAsText = client.post("http://0.0.0.0:8080/post-data") {
setBody(User("John", 42))
}.bodyAsText()
val user = client.get("http://0.0.0.0:8080/get-data").body<User>()
println("Userinfo: $bodyAsText")
println("Username: ${user.name}, age: ${user.age}")
}
}package com.example.model
data class User(val name: String, val age: Int)你可以在此处找到完整示例:client-custom-plugin-data-transformation。
身份验证
一个 Ktor 示例项目,演示了如果从服务器收到未授权响应,如何使用 on(Send) 钩子向 Authorization 标头添加 Bearer 令牌:
package com.example.plugins
import io.ktor.client.plugins.api.*
import io.ktor.http.*
val AuthPlugin = createClientPlugin("AuthPlugin", ::AuthPluginConfig) {
val token = pluginConfig.token
on(Send) { request ->
val originalCall = proceed(request)
originalCall.response.run { // this: HttpResponse
if(status == HttpStatusCode.Unauthorized && headers["WWW-Authenticate"]!!.contains("Bearer")) {
request.headers.append("Authorization", "Bearer $token")
proceed(request)
} else {
originalCall
}
}
}
}
class AuthPluginConfig {
var token: String = ""
}package com.example
import com.example.plugins.*
import com.example.server.*
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.*
fun main() {
startServer()
runBlocking {
val client = HttpClient(CIO) {
install(AuthPlugin) {
token = "abc123"
}
}
val response = client.get("http://0.0.0.0:8080/")
println(response.bodyAsText())
}
}你可以在此处找到完整示例:client-custom-plugin-auth。
