Martín Coll
Martín Coll

Reputation: 3794

Send application/x-www-form-urlencoded in Ktor

I can't figure out how to send a application/x-www-form-urlencoded POST request in Ktor. I see some submitForm helpers in Ktor's documentation but they don't send the request as expected.

What I want is to replicate this curl line behavior:

curl -d "param1=lorem&param2=ipsum" \
     -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
     https://webservice/endpoint

My dependency is on io.ktor:ktor-client-cio:1.0.0.

Upvotes: 20

Views: 9690

Answers (3)

ronny montaño
ronny montaño

Reputation: 31

Looking for information I found the way to do it

suspend inline fun <reified T> post(path: String, requestBody: FormDataContent): T {
    return apiClient.post() {
        url {
            encodedPath = path
            contentType(ContentType.Application.FormUrlEncoded)
        }
        setBody(requestBody)
    }.body()
}

Upvotes: 3

Mano Haran
Mano Haran

Reputation: 71

val response: HttpResponse = client.submitForm(
    url = "http://localhost:8080/get",
    formParameters = Parameters.build {
        append("first_name", "Jet")
        append("last_name", "Brains")
    },
    encodeInQuery = true
)



https://ktor.io/docs/request.html#form_parameters

Upvotes: 7

Mart&#237;n Coll
Mart&#237;n Coll

Reputation: 3794

After several tries I managed to send the request with the following code:

val url = "https://webservice/endpoint"
val client = HttpClient()
return client.post(url) {
    body = FormDataContent(Parameters.build {
        append("param1", "lorem")
        append("param2", "ipsum")
    })
}

Upvotes: 40

Related Questions