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

Time:02-25

Code below is to upload an file using ktor and 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}")
            })
        }
    )

CodePudding user response:

You can't do that using the submitFormWithBinaryData method. Use the post or request method. Here is an example:

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

CodePudding user response:

this is my code ...

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