kittinunf / fuel

The easiest HTTP networking library for Kotlin/Android
https://fuel.gitbook.io/documentation/
MIT License
4.57k stars 430 forks source link

Cannot generate `cUrlString()` with `.httpUpload()` #940

Open vojkny opened 3 months ago

vojkny commented 3 months ago
        val logoBytes: ByteArray = /** file to upload */
        val body = listOf(
            "Title" to name,
        )
        return "https://url-to-upload"
            .httpUpload(body)
            // TODO the InlineDataPart should better accept ByteArray instead of String
            .add(InlineDataPart(String(logoBytes), "Logo"))
            .cUrlString()

will fail with

 The inputs have already been written to an output stream and can not be consumed again.
    at com.github.kittinunf.fuel.core.requests.UploadBody.writeTo(UploadBody.kt:100)
    at com.github.kittinunf.fuel.core.requests.UploadBody.toByteArray(UploadBody.kt:76)
    at com.github.kittinunf.fuel.core.requests.RepeatableBody.toByteArray(RepeatableBody.kt:42)
    at com.github.kittinunf.fuel.core.extensions.FormattingKt.cUrlString(Formatting.kt:48)

Which is caused in:

fun Request.cUrlString(): String = buildString {
    …

    // body
    body(body.asRepeatable())
    val escapedBody = String(body.toByteArray()).replace("\"", "\\\"") <--- FAILS HERE on body.toByteArray()
  1. The InlineDataPart provides bytearray, so it is readable again
  2. For input streams, it could just show [input-stream-data] instead of such error

Also notice above, it would be better if InlineDataPart accepted ByteArray