发送应用程序/x-www-form-urlencoded in Ktor



我不知道如何在Ktor中发送application/x-www-form-urlencodedPOST请求。我在Ktor的文档中看到了一些submitForm助手,但他们没有按预期发送请求。

我想要的是复制这种卷曲线行为:

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

我依赖io.ktor:ktor-client-cio:1.0.0

经过几次尝试,我成功地用以下代码发送了请求:

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

为了寻找信息,我找到了的方法

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

最新更新