发送Ktor中的application / x-www-form-urlencoded

Mar*_*oll 2 urlencode kotlin ktor

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

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

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

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

Mar*_*oll 8

经过几次尝试,我设法用以下代码发送请求:

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

  • 我被这个问题困扰了一段时间,你的解决方案效果很好。谢谢! (2认同)

小智 5

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
Run Code Online (Sandbox Code Playgroud)