Search code examples
androidkotlinkotlin-multiplatformktor

How can I pass the body form-data in ktor?


            val response: HttpResponse = httpClient.post(endpoint) {
                headers {
                    append(HttpHeaders.Authorization, getAuthorizationHeader())
                }
                formData{
                    append("attachment", attachment)
                }
            }

the formData mentioned here is not correct it seems. This api works perfectly in postman when i pass the form-data in body tab. but i don't know how to do that here in ktor. i read the ktor documentation mentioned about that Here. but i am not clear how to do that. anyone please help me.

FYI, I'm new to kmm and ktor


Solution

  • I have found the answer after trying several times!

                val response: HttpResponse = httpClient.post(endpoint) {
                    headers {
                        append(HttpHeaders.Authorization, getAuthToken())
                    }
                    setBody(MultiPartFormDataContent(
                        formData {
                            append("attachment", attachment)}))
                }
    

    We can add key and value in body as form-data as string like shown in above!