I want to upload a byte stream with ktor-client. T...
# ktor
b
I want to upload a byte stream with ktor-client. The body is set to a
ByteReadChannel
, but then the
Content-Length
-header is not set. Setting it manually throws:
Copy code
Header(s) [Content-Length] are controlled by the engine and cannot be set explicitly
io.ktor.http.UnsafeHeaderException: Header(s) [Content-Length] are controlled by the engine and cannot be set explicitly
a
You can set
Content-Length
header by overriding
contentLength
property of an object of
OutgoingContent.ReadChannelContent
class. Here is an example:
Copy code
val client = HttpClient(Apache)

val channel = ByteChannel()
channel.writeStringUtf8("hello")
channel.close()

val r = <http://client.post|client.post><String>("<https://httpbin.org/post>") {
    body = object : OutgoingContent.ReadChannelContent() {
        override val contentLength: Long
            get() = 5

        override fun readFrom(): ByteReadChannel {
            return channel
        }
    }
}

println(r)
b
Thank you very much. Would be cool, when this were in the Docs :)