How to use OutputStream.writeBoundary method of com.github.kittinunf.fuel.core.requests.internal class

Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.internal.OutputStream.writeBoundary

UploadBody.kt

Source:UploadBody.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core.requests2import com.github.kittinunf.fuel.core.Body3import com.github.kittinunf.fuel.core.DataPart4import com.github.kittinunf.fuel.core.FuelError5import com.github.kittinunf.fuel.core.Headers6import com.github.kittinunf.fuel.core.Response7import com.github.kittinunf.fuel.core.representationOfBytes8import java.io.ByteArrayInputStream9import java.io.ByteArrayOutputStream10import java.io.InputStream11import java.io.OutputStream12import java.nio.charset.Charset13internal class BoundaryMissing(request: UploadRequest) : FuelError(14    IllegalArgumentException(15        "The Request is missing the boundary parameter in its Content-Type.\n\n" +16        "This can happen if you manually overwrite the Content-Type but forget to set a boundary. The boundary is \n" +17        "normally set automatically when you call \"request.upload()\". Remove manually setting the Content-Type or \n" +18        "add the boundary parameter to the Content-Type for this request: \n\n" +19            "\trequest.header(Headers.ContentType, \"multipart/form-data; boundary=custom-boundary\")"20    ),21    Response.error(request.url)22)23internal data class UploadBody(val request: UploadRequest) : Body {24    private var inputAvailable: Boolean = true25    /**26     * Represents this body as a string27     * @param contentType [String] the type of the content in the body, or null if a guess is necessary28     * @return [String] the body as a string or a string that represents the body such as (empty) or (consumed)29     */30    override fun asString(contentType: String?) = representationOfBytes("multipart/form-data")31    /**32     * Returns if the body is consumed.33     * @return [Boolean] if true, `writeTo`, `toStream` and `toByteArray` may throw34     */35    override fun isConsumed() = !inputAvailable36    /**37     * Returns the body emptiness.38     * @return [Boolean] if true, this body is empty39     */40    override fun isEmpty() = false41    /**42     * Returns the body as an [InputStream].43     *44     * @note callers are responsible for closing the returned stream.45     * @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again.46     *47     * @return the body as input stream48     */49    override fun toStream(): InputStream {50        throw UnsupportedOperationException(51            "Conversion `toStream` is not supported on UploadBody, because the source is not a single single stream." +52                    "Use `toByteArray` to write the contents to memory or `writeTo` to write the contents to a stream."53        )54    }55    /**56     * Returns the body as a [ByteArray].57     *58     * @note Because the body needs to be read into memory anyway, implementations may choose to make the [Body]59     *  readable once more after calling this method, with the original [InputStream] being closed (and release its60     *  resources). This also means that if an implementation choose to keep it around, `isConsumed` returns false.61     *62     * @return the entire body63     */64    override fun toByteArray(): ByteArray {65        return ByteArrayOutputStream(length?.toInt() ?: 32)66            .use { stream ->67                writeTo(stream)68                stream.toByteArray()69            }70            .also { result ->71                // The entire body is now in memory, and can act as a regular body72                request.body(DefaultBody.from(73                        { ByteArrayInputStream(result) },74                        { result.size.toLong() }75                ))76            }77    }78    /**79     * Writes the body to the [OutputStream].80     *81     * @note callers are responses for closing the [OutputStream].82     * @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again.83     * @note implementations are recommended to buffer the output stream if they can't ensure bulk writing.84     *85     * @param outputStream [OutputStream] the stream to write to86     * @return [Long] the number of bytes written87     */88    override fun writeTo(outputStream: OutputStream): Long {89        if (!inputAvailable) {90            throw FuelError.wrap(IllegalStateException(91                    "The inputs have already been written to an output stream and can not be consumed again."92            ))93        }94        inputAvailable = false95        val lazyDataparts = request.dataParts96        return outputStream.buffered().let { stream ->97            // Parameters98            val parameterLength = request.parameters.sumByDouble { (name, data) ->99                writeParameter(stream, name, data).toDouble()100            }101            // Blobs / Files102            val filesWithHeadersLength = lazyDataparts.sumByDouble { lazyDataPart ->103                writeDataPart(stream, lazyDataPart(request)).toDouble()104            }105            // Sum and Trailer106            val writtenLength = 0L +107                parameterLength +108                filesWithHeadersLength +109                stream.writeBoundary() + stream.writeString("--") +110                stream.writeNewline()111            // This is a buffered stream, so flush what's remaining112            writtenLength.toLong().also { stream.flush() }113        }114    }115    /**116     * Returns the length of the body in bytes117     * @return [Long?] the length in bytes, null if it is unknown118     */119    override val length: Long? by lazy {120        (121            // Parameters size122            request.parameters.sumByDouble { (name, data) ->123                writeParameter(ByteArrayOutputStream(), name, data).toDouble()124            } +125            // Blobs / Files size126            request.dataParts.sumByDouble { lazyDataPart ->127                val dataPart = lazyDataPart(request)128                // Allow for unknown sizes129                val length = dataPart.contentLength ?: return@lazy null130                if (length == -1L) return@lazy -1L131                0.0 + writeDataPartHeader(ByteArrayOutputStream(), dataPart) + length + CRLF.size132            } +133            // Trailer size134            "--$boundary--".toByteArray(DEFAULT_CHARSET).size + CRLF.size135        ).toLong()136    }137    private val boundary: String by lazy {138        request[Headers.CONTENT_TYPE].lastOrNull()139            ?.let { Regex("boundary=([^\\s]+)").find(it)?.groupValues?.getOrNull(1)?.trim('"') }140            ?: throw BoundaryMissing(request)141    }142    private fun writeParameter(outputStream: OutputStream, name: String, data: Any?): Long {143        outputStream.apply {144            return 0L +145                writeBoundary() +146                writeNewline() +147                writeString("${Headers.CONTENT_DISPOSITION}: form-data; name=\"$name\"") +148                writeNewline() +149                writeString("${Headers.CONTENT_TYPE}: text/plain; charset=\"${DEFAULT_CHARSET.name()}\"") +150                writeNewline() +151                writeNewline() +152                writeString(data.toString()) +153                writeNewline()154        }155    }156    private fun writeDataPart(outputStream: OutputStream, dataPart: DataPart): Long {157        outputStream.apply {158            val headerLength = writeDataPartHeader(outputStream, dataPart)159            val dataLength = dataPart.inputStream().use { it.copyTo(this) }160            return headerLength + dataLength + writeNewline()161        }162    }163    private fun writeDataPartHeader(outputStream: OutputStream, dataPart: DataPart): Long {164        outputStream.apply {165            return 0L +166                writeBoundary() +167                writeNewline() +168                writeString("${Headers.CONTENT_DISPOSITION}: ${dataPart.contentDisposition}") +169                writeNewline() +170                writeString("${Headers.CONTENT_TYPE}: ${dataPart.contentType}") +171                writeNewline() +172                writeNewline()173        }174    }175    private fun OutputStream.writeNewline() = writeBytes(CRLF)176    private fun OutputStream.writeBytes(bytes: ByteArray) = write(bytes).let { bytes.size.toLong() }177    private fun OutputStream.writeString(string: String, charset: Charset = DEFAULT_CHARSET) = writeBytes(string.toByteArray(charset))178    private fun OutputStream.writeBoundary() = writeString("--$boundary")179    companion object {180        val DEFAULT_CHARSET = Charsets.UTF_8181        private val CRLF = "\r\n".toByteArray(DEFAULT_CHARSET)182        fun from(request: UploadRequest): Body {183            return UploadBody(request).apply {184                inputAvailable = true185            }186        }187    }188}...

Full Screen

Full Screen

OutputStream.writeBoundary

Using AI Code Generation

copy

Full Screen

1private fun writeBoundary(outputStream: OutputStream, boundary: String) {2val boundaryBytes = boundary.toByteArray()3outputStream.write("--".toByteArray())4outputStream.write(boundaryBytes)5outputStream.write("\r6".toByteArray())7}8val boundary = "-----------------------------" + System.currentTimeMillis()9val boundaryBytes = boundary.toByteArray()10val boundaryLine = "--".toByteArray()11".toByteArray()12for (i in 0..3) {13outputStream.write(boundaryLine)14outputStream.write(boundaryBytes)15outputStream.write(crlf)16}17val boundaryLine = "--".toByteArray()18val boundaryBytes = boundary.toByteArray()19".toByteArray()20outputStream.write(boundaryLine)21outputStream.write(boundaryBytes)22outputStream.write(boundaryLine)23outputStream.write(crlf)24outputStream.flush()

Full Screen

Full Screen

OutputStream.writeBoundary

Using AI Code Generation

copy

Full Screen

1class FuelOutputStream(val stream: OutputStream) : OutputStream() {2    override fun write(b: Int) {3        stream.write(b)4    }5    fun writeBoundary(boundary: String) {6        stream.write(boundary.toByteArray())7    }8}9fun main() {10    val body = "Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r11    val fuelOutputStream = FuelOutputStream(System.out)12    fuelOutputStream.write(body.toByteArray())13    fuelOutputStream.writeBoundary(boundary)14}15Content-Disposition: form-data; name="file"; filename="test.txt"

Full Screen

Full Screen

OutputStream.writeBoundary

Using AI Code Generation

copy

Full Screen

1val outputStream = ByteArrayOutputStream()2val writer = OutputStreamWriter(outputStream)3writer.writeBoundary(boundary)4writer.write("Content-Disposition: form-data; name=\"file\"; filename=\"${file.name}\"\r5writer.write("Content-Type: ${file.contentType}\r6writer.flush()7val fileInputStream = FileInputStream(file)8val buffer = ByteArray(1024)9var bytesRead = fileInputStream.read(buffer)10while (bytesRead != -1) {11outputStream.write(buffer, 0, bytesRead)12bytesRead = fileInputStream.read(buffer)13}14outputStream.write("\r15".toByteArray())16outputStream.writeBoundary(boundary)17outputStream.write("--\r18".toByteArray())19outputStream.flush()20val body = outputStream.toByteArray()21request.body(body)22request.header("Content-Type" to "multipart/form-data; boundary=$boundary")23request.responseString { request, response, result ->24}25}26}

Full Screen

Full Screen

OutputStream.writeBoundary

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.core.requests.internal.writeBoundary2val boundary = "-----------------------------" + Random().nextInt().absoluteValue3val body = createBody(boundary)4val headers = listOf("Content-Type" to "multipart/form-data; boundary=$boundary")5val request = Request(Method.POST, url, headers, body)6val response = request.response()7println(response)8fun createBody(boundary: String): ByteArray {9    val bos = ByteArrayOutputStream()10".toByteArray()11    val twoHyphens = "--".toByteArray()12    val formField = "form_field".toByteArray()13    val formFieldValue = "form_field_value".toByteArray()14    out.writeBoundary(boundary)15    out.write(formField)16    out.write(lineEnd)17    out.write(formFieldValue)18    out.write(lineEnd)19    out.writeBoundary(boundary)20    out.write(twoHyphens)21    out.write(boundary.toByteArray())22    out.write(twoHyphens)23    out.write(lineEnd)24    return bos.toByteArray()25}26val response = Fuel.upload("/upload")27    .source { request, url ->28        File("/path/to/file")29    }30    .responseString()31	at com.github.kittinunf.fuel.core.requests.UploadTaskRequest.responseString(UploadTaskRequest.kt:37)32	at com.github.kittinunf.fuel.core.requests.UploadTaskRequest.responseString(UploadTaskRequest.kt:25)33	at com.github.kittinunf.fuel.core.requests.UploadTaskRequest.responseString$default(UploadTaskRequest.kt:24)34	at com.github.kittinunf.fuel.core.requests.UploadTaskRequest.responseString(UploadTaskRequest.kt:22)35	at com.github.kittinunf.fuel.core.requests.UploadTaskRequest.responseString$default(UploadTaskRequest.kt:21)

Full Screen

Full Screen

OutputStream.writeBoundary

Using AI Code Generation

copy

Full Screen

1val boundary = "--" + "boundary" + System.currentTimeMillis() + "--"2val boundaryBytes = boundary.toByteArray()3val outputStream = ByteArrayOutputStream()4val os = OutputStream.writeBoundary(outputStream, boundaryBytes)5os.close()6outputStream.close()7val boundary = "--" + "boundary" + System.currentTimeMillis() + "--"8val boundaryBytes = boundary.toByteArray()9val outputStream = ByteArrayOutputStream()10OutputStream.writeBoundary(outputStream, boundaryBytes)11outputStream.close()12val boundary = "--" + "boundary" + System.currentTimeMillis() + "--"13val boundaryBytes = boundary.toByteArray()14val outputStream = ByteArrayOutputStream()15OutputStream.writeBoundary(outputStream, boundaryBytes)16outputStream.close()17val boundary = "--" + "boundary" + System.currentTimeMillis() + "--"18val boundaryBytes = boundary.toByteArray()19val outputStream = ByteArrayOutputStream()20OutputStream.writeBoundary(outputStream, boundaryBytes)21outputStream.close()22val boundary = "--" + "boundary" + System.currentTimeMillis() + "--"23val boundaryBytes = boundary.toByteArray()24val outputStream = ByteArrayOutputStream()25OutputStream.writeBoundary(outputStream, boundaryBytes)26outputStream.close()27val boundary = "--" + "boundary" + System.currentTimeMillis() + "--"28val boundaryBytes = boundary.toByteArray()29val outputStream = ByteArrayOutputStream()30OutputStream.writeBoundary(outputStream, boundaryBytes)31outputStream.close()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful