I am using the http cio client -- how can I send a...
# ktor
r
I am using the http cio client -- how can I send an input stream to the client as the body?
Clearly I need to adapt the stream to an
OutgoingContent.WriteChannelContent
somehow, but its unclear to me how.
Actually, check that, I want to adapt a
java.io.Writer
(or
OutputStream
) to the body.
d
Copy code
suspend fun InputStream.toByteChannel(dispatcher: CoroutineDispatcher = ioCoroutineDispatcher): ByteReadChannel {
    val inputStream = this
    return writer(dispatcher) {
        while (true) {
            val temp = ByteArray(1024)
            val readSize = inputStream.read(temp)
            if (readSize <= 0) break
            channel.writeFully(temp, 0, readSize)
        }
    }.channel
}
Copy code
suspend fun OutputStream.toByteWriteChannel(dispatcher: CoroutineDispatcher = ioCoroutineDispatcher): ByteWriteChannel {
    val outputStream = this
    return reader(dispatcher) {
        while (true) {
            val temp = ByteArray(1024)
            val readSize = channel.readAvailable(temp)
            if (readSize <= 0) break
            outputStream.write(temp, 0, readSize)
        }
    }.channel
}
r
Thanks @Deactivated User, no built-ins for this? I see that coroutines io does have the analogue
ByteReadChannel.toInputStream()
.
Also, this assumes the existence of an
OutputStream
... I'd rather create an
OutputStream
connected to a
ByteWriteChannel
. So I think I just need to create a new
ByteWriteChannel
and call
toOutputStream
on it.
But where do I get the
ByteWriteChannel
from?
Can I just do
ByteChannel(true).toOutputStream()
?
d
I’m not sure if there are already for inputstream
Maybe for those cases there are already
r
Hmm, I'm still a little confused. I want to create a
OutgoingContent
that is a
ByteWriteChannel
, from which it looks like I can do
toOutputStream
. But it seems that class is internal, so I don't have a way to create it.
@Deactivated User ideas?
d
Sorry, was AFK
What about WriterContent?
WriterContent({ … channel.write(…)… }, ContentType…)
OutgoingContent
has several abstract inner classes, (if you look at the implementations of those classes)
r
So if I pass in an implementation of
WriteChannelContent
I'll get a
writeTo
callback in which I can write to the output stream?
if you have a bytewritechannel, I guess you can copy from one to another
r
@Deactivated User
WriterContent
worked as expected, BUT I note this class is in the server-core package, so it cannot easily be used as
OutgoingContent
in the ktor client. Should this and other implementations of
OutgoingContent
be moved to somewhere common to client and server?
d
I would file an issue suggesting it: https://github.com/ktorio/ktor/issues
r