ktor 客户端发布多部分/表单数据

2024-05-07

如何使用 ktor 客户端将文件作为多部分/表单数据发布?我想将它用于电报机器人 API“发送文档”。 我需要获得与curl命令相同的结果

curl -F document=@"path/to/some.file" https://api.telegram.org/bot<token>/sendDocument?chat_id=<chat_id>

您可以使用提交带有二进制数据的表单 https://api.ktor.io/ktor-client/ktor-client-core/ktor-client-core/io.ktor.client.request.forms/submit-form-with-binary-data.html发送方法多部分/表单数据请求 https://ktor.io/docs/request.html#upload_file。这是一个解决方案:

val client = HttpClient(Apache) {}

val file = File("path/to/some.file")
val chatId = "123"

client.submitFormWithBinaryData(
    url = "https://api.telegram.org/bot<token>/sendDocument?chat_id=$chatId",
    formData = formData {
        append("document", file.readBytes(), Headers.build {
            append(HttpHeaders.ContentDisposition, "filename=${file.name}")
        })
    }
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ktor 客户端发布多部分/表单数据 的相关文章

随机推荐