How to create a post request for application/x-www-form-urlencoded content type in ktor client android

116 Views Asked by At

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-urlencoded value.
  • 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.

1

There are 1 best solutions below

0
Mubashir P A On

After a some changes i fixed the request.

Working code

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()