我想在
application/x-www-form-urlencoded
android 中创建 ktor client
内容类型的发布请求。
application/x-www-form-urlencoded
值。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
}
)
}
}
}
}
每次我都会遇到错误。
经过一些更改后,我修复了请求。
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()