https://kotlinlang.org logo
#ktor
Title
# ktor
b

benkuly

09/17/2021, 10:58 AM
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

Aleksei Tirman [JB]

09/17/2021, 11:41 AM
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

benkuly

09/17/2021, 11:58 AM
Thank you very much. Would be cool, when this were in the Docs :)
59 Views