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

Android中使用Ktor Client创建application/x-www-form-urlencoded类型POST请求

在Android Ktor Client中正确实现Spotify令牌请求(application/x-www-form-urlencoded类型POST)

正确实现代码

要发送符合要求的application/x-www-form-urlencoded类型POST请求,需使用Ktor的FormDataContent配合Parameters构建请求体,确保参数名与Spotify要求完全匹配:

// 发送请求并解析响应
val tokenResponse = httpClient.post("https://accounts.spotify.com/api/token") {
    // 指定请求的Content-Type
    contentType(ContentType.Application.FormUrlEncoded)
    // 构建form格式的请求体
    setBody(FormDataContent(Parameters.build {
        append("grant_type", "client_credentials")
        append("client_id", "你的实际client_id")
        append("client_secret", "你的实际client_secret")
    }))
}.body<SpotifyTokenResponse>()

// 定义用于解析响应的序列化数据类
@Serializable
data class SpotifyTokenResponse(
    @SerialName("access_token") val accessToken: String,
    @SerialName("token_type") val tokenType: String,
    @SerialName("expires_in") val expiresIn: Long
)

你之前写法的问题分析

  1. 注释的FormDataContent代码:参数名错误,Spotify要求的是client_id和client_secret,但你写的是clientId和clientSecret,导致参数无法被Spotify端点识别。
  2. ClientCredentials数据类写法:ContentNegotiation的Json转换器仅处理JSON格式请求体,而这里需要的是form编码格式,直接传入数据类会导致请求体格式错误。
  3. 直接传入List的写法:Ktor无法自动将List转换为form编码的请求体,必须用FormDataContent包装Parameters对象。

保留HttpClient的ContentNegotiation配置

如果你的项目中其他请求需要处理JSON,原有的HttpClient配置可以保留,不会影响form请求的发送:

val ktorModule = module {
    single {
        HttpClient {
            install(ContentNegotiation) {
                json(
                    Json {
                        prettyPrint = true
                        isLenient = true
                        ignoreUnknownKeys = true
                        useAlternativeNames = false
                    }
                )
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Mubashir P A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:42:41