カスタムクライアントプラグイン
コード例: client-custom-plugin
v2.2.0以降、Ktorはカスタムクライアントプラグインを作成するための新しいAPIを提供しています。通常、このAPIを使用する際に、パイプラインやフェーズといったKtorの内部概念を理解する必要はありません。 代わりに、onRequestやonResponseなどの一連のハンドラーを使用して、リクエストとレスポンスの処理におけるさまざまなステージにアクセスできます。
最初のプラグインの作成とインストール
このセクションでは、各リクエストにカスタムヘッダーを追加する最初のプラグインを作成してインストールする方法を説明します。
プラグインを作成するには、createClientPlugin関数を呼び出し、プラグイン名を引数として渡します。
kotlinpackage com.example.plugins import io.ktor.client.plugins.api.* val CustomHeaderPlugin = createClientPlugin("CustomHeaderPlugin") { // Configure the plugin ... }この関数は、プラグインをインストールするために使用される
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。 以降のセクションでは、プラグイン設定の提供方法や、リクエストとレスポンスの処理方法について見ていきます。
プラグイン設定の提供
前のセクションでは、あらかじめ定義されたカスタムヘッダーを各リクエストに追加するプラグインの作成方法を説明しました。このプラグインをより汎用的にするために、任意のカスタムヘッダー名と値を渡せる設定(Configuration)を提供してみましょう。
まず、設定クラスを定義する必要があります。
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メソッド、ヘッダー、リクエストボディなどのさまざまなリクエストパラメータの指定方法について学びます。ごとに実行され、レスポンスのロギングやクッキーの保存など、さまざまな方法でインスペクション(検証・調査)できます。 |
transformResponseBody | レスポンスボディを変換できます。 このハンドラーは各 例: データ変換 |
onClose | このプラグインによって割り当てられたリソースをクリーンアップできます。 このハンドラーはクライアントがクローズされたときに呼び出されます。 |
| ハンドラー | 説明 |
on(SetupRequest) | SetupRequest フックは、リクエスト処理の最初に実行されます。 |
onRequest | このハンドラーは各HTTPリクエストリクエストの送信方法と、リクエストURL、HTTPメソッド、ヘッダー、リクエストボディなどのさまざまなリクエストパラメータの指定方法について学びます。ごとに実行され、それを変更することができます。 例: カスタムヘッダー |
transformRequestBody | リクエストボディを変換できます。 このハンドラーでは、ボディを OutgoingContent (例えば、 例: データ変換 |
on(Send) |
例: 認証 |
on(SendingRequest) |
console |
onResponse | このハンドラーは受信したHTTPレスポンスリクエストの送信方法と、リクエストURL、HTTPメソッド、ヘッダー、リクエストボディなどのさまざまなリクエストパラメータの指定方法について学びます。ごとに実行され、レスポンスのロギングやクッキーの保存など、さまざまな方法でインスペクション(検証・調査)できます。 |
transformResponseBody | レスポンスボディを変換できます。 このハンドラーは各 例: データ変換 |
onClose | このプラグインによって割り当てられたリソースをクリーンアップできます。 このハンドラーはクライアントがクローズされたときに呼び出されます。 |
呼び出し状態の共有
カスタムプラグインを使用すると、呼び出しに関連する任意の値を共有できるため、その呼び出しを処理する任意のハンドラー内からその値にアクセスできます。 この値は、call.attributes コレクション内に一意のキーを持つ属性(Attribute)として保存されます。 以下の例は、属性を使用してリクエストの送信からレスポンスの受信までの時間を計算する方法を示しています。
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。
クライアント設定へのアクセス
HttpClient インスタンスを返す client プロパティを使用して、クライアント設定にアクセスできます。 以下の例は、クライアントが使用しているプロキシアドレスを取得する方法を示しています。
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。
認証
サーバーから未認証レスポンスを受信した場合に、on(Send) フックを使用して Authorization ヘッダーにベアラートークンを追加する方法を示すサンプルのKtorプロジェクトです。
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。
