I want to create a post request for application/x-www-form-urlencoded content type in ktor client android.
Request an access token
- Send a POST request to the token endpoint URI.
- Add the Content-Type header set to the
application/x-www-form-urlencodedvalue. - Add a HTTP body containing the Client ID and Client Secret, along with the grant_type parameter set to client_credentials.
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"
I want to send this request using ktor client in android. How to do that?
Code I tried
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
}
)
}
}
}
}
Each time i am getting errors.
After a some changes i fixed the request.
Working code