@@ -8,24 +8,25 @@ import io.ktor.http.HeadersBuilder
88import io.ktor.http.HttpHeaders
99import io.ktor.http.HttpStatusCode
1010import io.ktor.http.content.OutgoingContent
11- import io.ktor.http.content.UnsupportedContentTypeException
1211import io.ktor.utils.io.ByteReadChannel
13- import io.ktor.utils.io.core.readByteArray
14- import io.ktor.utils.io.readRemaining
12+ import io.ktor.utils.io.readAvailable
1513import io.ktor.utils.io.writer
1614import kotlinx.coroutines.DelicateCoroutinesApi
1715import kotlinx.coroutines.GlobalScope
16+ import kotlinx.io.Buffer
17+ import kotlinx.io.readByteArray
1818import kotlin.coroutines.coroutineContext
1919
2020fun createAndroidNativePlatformHttpClient (block : HttpClientConfig <* >.() -> Unit = {}): HttpClient = HttpClient (MockEngine ) {
2121 block(this )
2222 engine {
2323 addHandler { request ->
24+ val requestBody = request.body.toByteArray()
2425 val response = executeBinaryRequest(
2526 method = request.method.value,
2627 url = request.url.toString(),
2728 headers = request.headers.entries().associate { (name, values) -> name to values.joinToString(" ," ) },
28- body = request.body.toByteChannel().readRemaining().readByteArray() .takeIf { it.isNotEmpty() },
29+ body = requestBody .takeIf { it.isNotEmpty() },
2930 contentType = request.headers[HttpHeaders .ContentType ],
3031 followRedirects = false ,
3132 )
@@ -57,5 +58,21 @@ private suspend fun OutgoingContent.toByteChannel(): ByteReadChannel = when (thi
5758 is OutgoingContent .ReadChannelContent -> readFrom()
5859 is OutgoingContent .NoContent -> ByteReadChannel .Empty
5960 is OutgoingContent .ContentWrapper -> delegate().toByteChannel()
60- is OutgoingContent .ProtocolUpgrade -> throw UnsupportedContentTypeException (this )
61+ is OutgoingContent .ProtocolUpgrade -> error(" Protocol upgrade is not supported on Android Native platform HTTP bridge" )
62+ }
63+
64+ private suspend fun OutgoingContent.toByteArray (): ByteArray {
65+ val channel = toByteChannel()
66+ val sink = Buffer ()
67+ while (true ) {
68+ val read = channel.readAvailable(1 ) { source: Buffer ->
69+ val bytes = source.readByteArray()
70+ sink.write(bytes)
71+ bytes.size
72+ }
73+ if (read <= 0 ) {
74+ break
75+ }
76+ }
77+ return sink.readByteArray()
6178}
0 commit comments