Reputation: 3794
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
.
Upvotes: 20
Views: 9690
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
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
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