如何在 ktor 客户端 android 中创建 application/x-www-form-urlencoded 内容类型的发布请求

问题描述 投票:0回答:1

我想在

application/x-www-form-urlencoded
android 中创建
ktor client
内容类型的发布请求。

请求访问令牌

  • 向令牌端点 URI 发送 POST 请求。
  • 将 Content-Type 标头设置为
    application/x-www-form-urlencoded
    值。
  • 添加包含客户端 ID 和客户端密钥的 HTTP 正文,以及设置为 client_credentials 的 grant_type 参数。
curl -X POST "https://accounts.spotify.com/api/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id=your-client-id&client_secret=your-client-secret"

我想在android中使用

ktor client
发送此请求。如何做到这一点?

我尝试过的代码

httpClient.post(Spotify.TOKEN_ENDPOINT_URI) {

            contentType(ContentType.Application.FormUrlEncoded)

//            setBody(FormDataContent(Parameters.build {
//                append("grant_type", "client_credentials")
//                append("clientId", "123")
//                append("clientSecret", "123")
//            }))

//            setBody(
//                ClientCredentials(
//                    clientId = "123",
//                    clientSecret = "123"
//                )
//            )

            setBody(
                listOf(
                    "grant_type" to "client_credentials",
                    "client_id" to "123",
                    "client_secret" to "123"
                )
            )
}
@Serializable
data class ClientCredentials(
    @SerialName("grant_type")
    val grantType: String = "client_credentials",
    @SerialName("client_id")
    val clientId: String,
    @SerialName("client_secret")
    val clientSecret: String
)
val ktorModule = module {
    single {
        HttpClient {
            install(ContentNegotiation) {
                json(
                    Json {
                        prettyPrint = true
                        isLenient = true
                        ignoreUnknownKeys = true
                        useAlternativeNames = false
                    }
                )
            }
        }
    }
}

每次我都会遇到错误。

android kotlin post kotlin-multiplatform ktor-client
1个回答
0
投票

经过一些更改后,我修复了请求。

工作代码

import io.ktor.client.request.forms.FormDataContent
import io.ktor.http.Parameters

httpClient.post(Spotify.TOKEN_ENDPOINT_URI) {
    contentType(ContentType.Application.FormUrlEncoded)
    setBody(
        FormDataContent(
            Parameters.build {
                append(Spotify.Parameters.GRANT_TYPE, Spotify.Parameters.CLIENT_CREDENTIALS)
                append(Spotify.Parameters.CLIENT_ID, "client-id")
                append(Spotify.Parameters.CLIENT_SECRET, "client-secret")
            }
        )
    )
}.body()
© www.soinside.com 2019 - 2024. All rights reserved.