Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 924
Martín Coll Avatar asked Dec 03 '18 14:12

Martín Coll


People also ask

Is KTOR better than Retrofit?

What's KTor Client and how is it different from Retrofit for Android? Ktor client is an HTTP client that can be used for making requests and handling responses. It works pretty similar to Retrofit but what makes it stand out is that it is not wired to anything android specific and is completely Kotlin powered.

How do I encode URL in Kotlin?

Simply enter your data then push the encode button. To encode binaries (like images, documents, etc.) use the file upload form a little further down on this page.


2 Answers

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")
    })
}
like image 182
Martín Coll Avatar answered Oct 17 '22 19:10

Martín Coll


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
like image 1
Mano Haran Avatar answered Oct 17 '22 17:10

Mano Haran