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

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

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.writeBytes

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.core.requests.internal2val bytes = data.toByteArray()3val outputStream = ByteArrayOutputStream()4internal.writeBytes(outputStream, bytes)5val result = outputStream.toString()6println(result)7import com.github.kittinunf.fuel.core.requests.internal8val bytes = data.toByteArray()9val outputStream = ByteArrayOutputStream()10internal.writeBytes(outputStream, bytes)11val result = outputStream.toString()12println(result)

Full Screen

Full Screen

OutputStream.writeBytes

Using AI Code Generation

copy

Full Screen

1val request = Fuel.post(url, headers = listOf("Content-Type" to "application/octet-stream"))2val response = request.body(data).response()3val request = Fuel.post(url, headers = listOf("Content-Type" to "application/octet-stream"))4val response = request.body(data).response()5val file = File("file.txt")6val request = Fuel.upload("/api/upload", listOf("file" to file))7val response = request.response()8val file = File("file.txt")9val request = Fuel.upload("/api/upload", listOf("file" to file))10val response = request.response()11val file = File("file.txt")12val request = Fuel.upload("/api/upload", listOf("file" to file))13val response = request.response()14val file = File("file.txt")15val request = Fuel.upload("/api/upload", listOf("file" to file))16val response = request.response()

Full Screen

Full Screen

OutputStream.writeBytes

Using AI Code Generation

copy

Full Screen

1 val bytes = "hello world".toByteArray()2 val outStream = ByteArrayOutputStream()3 outStream.writeBytes(bytes)4 val byteArray = outStream.toByteArray()5 println("byteArray: $byteArray")6 val inputStream = ByteArrayInputStream(byteArray)7 val bytes2 = inputStream.readBytes()8 println("bytes2: $bytes2")9 println("bytes2 string: ${String(bytes2)}")10 val inputStream2 = ByteArrayInputStream(byteArray)11 val bytes3 = inputStream2.readBytes()12 println("bytes3: $bytes3")13 println("bytes3 string: ${String(bytes3)}")14}15import com.github.kittinunf.fuel.Fuel16import com.github.kittinunf.fuel.core.FuelManager17import com.github.kittinunf.fuel.core.Request18import com.github.kittinunf.fuel.core.Response19import com.github.kittinunf.fuel.gson.responseObject20import com.github.kittinunf.fuel.httpPost21import com.github.kittinunf.result

Full Screen

Full Screen

OutputStream.writeBytes

Using AI Code Generation

copy

Full Screen

1val connection = url.openConnection() as HttpURLConnection2val outputStream = connection.getOutputStream()3outputStream.writeBytes(“{“name”:”Test”}”)4outputStream.flush()5outputStream.close()6connection.connect()7connection.disconnect()8val connection = url.openConnection() as HttpURLConnection9val outputStream = connection.getOutputStream()10outputStream.writeBytes(“{“name”:”Test”}”)11outputStream.flush()12outputStream.close()13connection.connect()14connection.disconnect()15import os16import sys17import time18print('Hello')19time.sleep(10)20print('World')21""".trimIndent()22val scriptFile = File.createTempFile("script", ".py")23scriptFile.writeText(script)24val command = arrayOf("python", scriptFile.absolutePath)25val process = ProcessBuilder(*command)26 .redirectErrorStream(true)27 .start()28val output = process.inputStream.bufferedReader().readText()29println(output)30import os31import sys32import time33print('Hello')34time.sleep(10)35print('World')

Full Screen

Full Screen

OutputStream.writeBytes

Using AI Code Generation

copy

Full Screen

1fuelManager.upload("/upload")2 .source { request, url ->3 val file = File("/path/to/file")4 val bytes = file.readBytes()5 ByteArrayInputStream(bytes)6 }7 .response { _, _, result ->8 }9fuelManager.upload("/upload")10 .source { request, url ->11 val file = File("/path/to/file")12 val stream = file.inputStream()13 }14 .response { _, _, result ->15 }16fuelManager.upload("/upload")17 .source { request, url ->18 val file = File("/path/to/file")19 val bytes = file.readBytes()20 ByteArrayInputStream(bytes)21 }22 .response { _, _, result ->23 }24fuelManager.upload("/upload")25 .source { request, url ->26 val file = File("/path/to/file")27 val stream = file.inputStream()28 }29 .response { _, _, result ->30 }

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