如果我使用submitFormWithBinaryData(),如何向 ktor 请求添加标头?

daw*_*oud 3 android kotlin ktor kotlin-multiplatform kmm

下面的代码是使用 ktor 和 kmm 上传文件......

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

Ale*_*man 5

你不能使用该submitFormWithBinaryData方法来做到这一点。使用postrequest方法。这是一个例子:

client.post("https://api.telegram.org/bot<token>/sendDocument?chat_id=$chatId") {
    header("custom", "value")
    body = MultiPartFormDataContent(formData {
        append("document", file.readBytes(), Headers.build {
            append(HttpHeaders.ContentDisposition, "filename=${file.name}")
        })
    })
}
Run Code Online (Sandbox Code Playgroud)