【问题标题】:Send application/x-www-form-urlencoded in Ktor在 Ktor 中发送 application/x-www-form-urlencoded
【发布时间】:2019-05-04 20:28:02
【问题描述】:

我不知道如何在 Ktor 中发送 application/x-www-form-urlencoded POST 请求。我在 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

【问题讨论】:

    标签: kotlin urlencode ktor


    【解决方案1】:
    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
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

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

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

    【讨论】:

    • 我被这个问题困扰了一段时间,你的解决方案效果很好。谢谢!
    • 谢谢!有很多方法可以做到这一点......这似乎是最简单的!
    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多