哪个客户 post multipart/form-data

ktor client post multipart/form-data

我如何post file as multipart/form-data 使用 ktor 客户端?我想将它用于电报机器人 API“发送文档”。 我需要达到与 curl 命令相同的结果

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

您可以使用submitFormWithBinaryData method to send mutlipart/form-data request。这是一个解决方案:

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}")
        })
    }
)