Default Request

预计阅读时间:2分钟

此功能使您可以为特定客户端的所有请求配置一些默认设置.

此功能在io.ktor.client.features.defaultRequest方法中定义,并且不需要其他构件.

Installation

在配置客户端时,此功能提供了一种扩展方法来为此客户端设置默认值. 例如,如果要向所有请求添加标头,或者配置主机,端口和方法,或者仅设置路径.

val client = HttpClient() {
    defaultRequest { // this: HttpRequestBuilder ->
        method = HttpMethod.Head
        host = "127.0.0.1"
        port = 8080
        header("X-My-Header", "MyValue")
    }
}

Example

一个显示客户端如何使用MockEngine表现的示例

import io.ktor.client.*
import io.ktor.client.engine.*
import io.ktor.client.engine.mock.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.io.*

fun main(args: Array<String>) = runBlocking {
    val client = HttpClient(MockEngine) {
        engine {
            // Register request handler.
            addHandler { request ->
                with(request) {
                    val responseText = buildString{
                        append("method=$method,")
                        append("host=${url.host},")
                        append("port=${url.port},")
                        append("path=${url.fullPath},")
                        append("headers=$headers")
                    }
                    val responseHeaders = headersOf("Content-Type" to listOf(ContentType.Text.Plain.toString()))

                    respond(responseText, headers = responseHeaders)
                }
            }
        }

        // Configure default request feature.
        defaultRequest {
            method = HttpMethod.Head
            host = "127.0.0.1"
            port = 8080
            header("X-My-Header", "MyValue")
        }
    }

    val result = client.get<String> {
        url {
            encodedPath = "/demo"
        }
    }

    println(result)
    // Prints: method=HttpMethod(value=HEAD), host=127.0.0.1, port=8080, path=/demo, headers=Headers [X-My-Header=[MyValue], Accept=[*/*]]
}

by  ICOPY.SITE