如果我使用 submitFormWithBinaryData(),如何将 headers 添加到 ktor 请求?

How can i add headers to ktor request if i use submitFormWithBinaryData()?

下面的代码是使用 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}")
            })
        }
    )

您不能使用 submitFormWithBinaryData 方法做到这一点。使用 post or request 方法。这是一个例子:

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

这是我的代码...

     val response = client.post<String>("${PublicData.BASEURL}"+"classes/UserFiles"){
                headers {
                    append("X-Parse-Application-Id", PublicData.Application_Id )
                    append("X-Parse-REST-API-Key", PublicData.REST_API_Key)
                    append("Content-Type", "application/json")
                }
    
                contentType(ContentType.Application.Json)
                body =  MultiPartFormDataContent(formData {
                    headersOf("X-Parse-Application-Id", PublicData.Application_Id)
                    headersOf("X-Parse-REST-API-Key", PublicData.REST_API_Key)
                    append("file_type", "Ktor klogo")
                    append("encryption_tool_id", "Ktorkk logo")
                    append("user_id", "Ktor kklogo")
                    append("query", "Ktor kklogo")
                    append("file", file, Headers.build {
                        append(HttpHeaders.ContentType, ContentType.Application.Json)
                        append(HttpHeaders.ContentDisposition, "filename=asd")
                    })
                })
    
            }