Skip to content

Commit 9f34051

Browse files
committed
fix(android-native): route all platform http through native https bridge
1 parent 393dc22 commit 9f34051

1 file changed

Lines changed: 22 additions & 5 deletions

File tree

android-https-native/src/androidNativeArm64Main/kotlin/org/ntqqrev/androidhttps/AndroidNativePlatformHttpClient.kt

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,25 @@ import io.ktor.http.HeadersBuilder
88
import io.ktor.http.HttpHeaders
99
import io.ktor.http.HttpStatusCode
1010
import io.ktor.http.content.OutgoingContent
11-
import io.ktor.http.content.UnsupportedContentTypeException
1211
import 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
1513
import io.ktor.utils.io.writer
1614
import kotlinx.coroutines.DelicateCoroutinesApi
1715
import kotlinx.coroutines.GlobalScope
16+
import kotlinx.io.Buffer
17+
import kotlinx.io.readByteArray
1818
import kotlin.coroutines.coroutineContext
1919

2020
fun 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

Comments
 (0)