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¶m2=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
.
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.
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.
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")
})
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With