You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ktor Client Builder请求中未展示Basic认证Header问题

Ktor Client Auth插件未自动添加Basic认证Header问题

问题重现

我通过Ktor Client DSL配置Auth插件实现Basic认证,代码如下:

import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.auth.*
import io.ktor.client.plugins.auth.providers.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.runBlocking

val client = HttpClient(OkHttp) {
    install(Auth) {
        basic {
            credentials {
                BasicAuthCredentials(email, token)
            }
        }
    }
    install(Logging) {
        logger = Logger.DEFAULT
        level = LogLevel.ALL
    }
}

但请求日志中并未出现预期的Basic认证Header:

15:47:14.589 [DefaultDispatcher-worker-3] INFO io.ktor.client.HttpClient - REQUEST: https://example.url.net/api
METHOD: HttpMethod(value=GET)
COMMON HEADERS
-> Accept: */*
-> Accept-Charset: UTF-8
// >>> 本该在此处出现 <<<
CONTENT HEADERS
-> Content-Length: 0
BODY Content-Type: null
BODY START

而手动为GET请求添加认证Header时,请求能正常携带Header:

fun search() {
    runBlocking {
        val response: HttpResponse = client.get(url) {
            headers {
                append(HttpHeaders.Authorization, "Basic $auth")
            }
        }
        println(response.bodyAsText())
    }
}

此时日志中能看到正确的认证Header:

15:49:47.407 [DefaultDispatcher-worker-3] INFO io.ktor.client.HttpClient - REQUEST: https://example.url.net/api
METHOD: HttpMethod(value=GET)
COMMON HEADERS
-> Accept: */*
-> Accept-Charset: UTF-8
-> Authorization: Basic fwouwneg34g38gngwg // 此处已出现
CONTENT HEADERS
-> Content-Length: 0
BODY Content-Type: null
BODY START

注意:我在Kotlin Multiplatform桌面JVM环境中使用的依赖如下:

implementation("io.ktor:ktor-client-core:2.1.0")
implementation("io.ktor:ktor-client-okhttp:2.1.0")
implementation("io.ktor:ktor-client-auth:2.1.0")
implementation("io.ktor:ktor-client-logging:2.1.0")
implementation("ch.qos.logback:logback-classic:1.3.0-beta0")

内容的提问来源于stack exchange,提问作者Pedro Romano Barbosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:03:35