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

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

DefaultRequest.kt

Source:DefaultRequest.kt Github

copy

Full Screen

...222 * @param charset [Charset] the charset to write with223 * @return [Request] the request224 */225 override fun body(body: String, charset: Charset): Request =226 body(bytes = body.toByteArray(charset), charset = charset)227 .let {228 if (header(Headers.CONTENT_TYPE).lastOrNull().isNullOrBlank())229 header(Headers.CONTENT_TYPE, "text/plain; charset=${charset.name()}")230 else it231 }232 /**233 * Sets the body to the contents of a file.234 *235 * @note this does *NOT* make this a multipart upload. For that you can use the upload request. This function can be236 * used if you want to upload the single contents of a text based file as an inline body.237 *238 * @note when charset is not UTF-8, this forces the client to use chunked encoding, because file.length() gives the239 * length of the file in bytes without considering the charset. If the charset is to be considered, the file needs240 * to be read in its entirety which defeats the purpose of using a file....

Full Screen

Full Screen

Kkiapay.kt

Source:Kkiapay.kt Github

copy

Full Screen

...217 }218 private fun reduceBitmap(original: Bitmap): Bitmap {219 val out = ByteArrayOutputStream()220 original.compress(Bitmap.CompressFormat.WEBP, 100, out)221 return BitmapFactory.decodeStream(ByteArrayInputStream(out.toByteArray()))222 }223}224internal class RequestPaymentAction(private val user: User) {225 operator fun invoke(activity: AppCompatActivity, sdkConfig: SdkConfig){226 activity.startActivityForResult(227 Intent(activity, CustomTabActivity::class.java).apply {228 putExtra(CustomTabActivity.EXTRA_URL,229 "$KKIAPAY_URL/?=${user.toBase64(activity.applicationContext, sdkConfig)}")230 putExtra(CustomTabActivity.EXTRA_THEME,231 sdkConfig.themeColor)232 }, KKIAPAY_REQUEST_CODE)233 }234}235internal data class User(val amount: String = "",236 val reason: String = "",237 val name: String = "",238 val key: String = "",239 val callback: String,240 val phone: String = "",241 val sdk: String = "android",242 val theme: String = "",243 val url: String = "",244 val sandbox: Boolean,245 val host: String? = "",246 val data: String = ""247) {248 fun toBase64(context: Context, sdkConfig: SdkConfig) : String{249 val preConvertion = this.copy(250 theme = sdkConfig.color,251 url = sdkConfig.imageUrl,252 host = context.applicationContext.packageName253 )254 val userJson = Gson().toJson(preConvertion).toString()255 return String(Base64.encodeBase64(userJson.toByteArray()))256 }257}258private sealed class SandBoxKKiapayApi : FuelRouting {259 override val basePath: String260 get() = "https://api-sandbox.kkiapay.me"261 override val headers: Map<String, HeaderValues>?262 get() = mapOf("x-api-key" to listOf(KKiapayApi.apiKey))263 override val method: Method264 get() = Method.POST265 override val body: String?266 get() = null267 override val bytes: ByteArray?268 get() = null269 override val params: Parameters?...

Full Screen

Full Screen

KubernetesApiSpec.kt

Source:KubernetesApiSpec.kt Github

copy

Full Screen

...358 FuelManager.instance.client = object : Client {359 override fun executeRequest(request: Request): Response {360 sentRequest = request361 return Response().apply {362 data = podJson.toByteArray()363 httpStatusCode = 200364 httpResponseMessage = "OK"365 }366 }367 }368 }369 afterGroup {370 //Restore the Fuel Client371 FuelManager.instance.client = oldClient372 }373 it("should send the correct request, and return the PodDescription structure") {374 val result = fetchPodDescription("some-pod-name", "some-namespace")375 assertEquals(podDescription, result)376 assertEquals(...

Full Screen

Full Screen

Request.kt

Source:Request.kt Github

copy

Full Screen

...35 val httpBody: ByteArray36 get() {37 return ByteArrayOutputStream().apply {38 bodyCallback?.invoke(request, this, 0)39 }.toByteArray()40 }41 lateinit var client: Client42 //headers43 val httpHeaders = mutableMapOf<String, String>()44 //params45 var parameters = listOf<Pair<String, Any?>>()46 var name = ""47 val names = mutableListOf<String>()48 val mediaTypes = mutableListOf<String>()49 //underlying task request50 val taskRequest: TaskRequest by lazy {51 when (type) {52 Type.DOWNLOAD -> DownloadTaskRequest(this)53 Type.UPLOAD -> UploadTaskRequest(this)54 else -> TaskRequest(this)55 }56 }57 var taskFuture: Future<*>? = null58 //configuration59 var socketFactory: SSLSocketFactory? = null60 var hostnameVerifier: HostnameVerifier? = null61 //callers62 lateinit var executor: ExecutorService63 lateinit var callbackExecutor: Executor64 //interceptor65 var requestInterceptor: ((Request) -> Request)? = null66 var responseInterceptor: ((Request, Response) -> Response)? = null67 //interfaces68 fun timeout(timeout: Int): Request {69 timeoutInMillisecond = timeout70 return this71 }72 fun timeoutRead(timeout: Int): Request {73 timeoutReadInMillisecond = timeout74 return this75 }76 fun header(vararg pairs: Pair<String, Any>?): Request {77 pairs.forEach {78 if (it != null)79 httpHeaders.plusAssign(Pair(it.first, it.second.toString()))80 }81 return this82 }83 fun header(pairs: Map<String, Any>?): Request = header(pairs, true)84 internal fun header(pairs: Map<String, Any>?, replace: Boolean): Request {85 pairs?.forEach {86 it.let {87 if (!httpHeaders.containsKey(it.key) || replace) {88 httpHeaders.plusAssign(Pair(it.key, it.value.toString()))89 }90 }91 }92 return this93 }94 fun body(body: ByteArray): Request {95 bodyCallback = { request, outputStream, totalLength ->96 outputStream?.write(body)97 body.size.toLong()98 }99 return this100 }101 fun body(body: String, charset: Charset = Charsets.UTF_8): Request = body(body.toByteArray(charset))102 fun authenticate(username: String, password: String): Request {103 val auth = "$username:$password"104 val encodedAuth = Base64.encode(auth.toByteArray(), Base64.NO_WRAP)105 return header("Authorization" to "Basic " + String(encodedAuth))106 }107 fun progress(handler: (readBytes: Long, totalBytes: Long) -> Unit): Request {108 if (taskRequest as? DownloadTaskRequest != null) {109 val download = taskRequest as DownloadTaskRequest110 download.apply {111 progressCallback = handler112 }113 } else if (taskRequest as? UploadTaskRequest != null) {114 val upload = taskRequest as UploadTaskRequest115 upload.apply {116 progressCallback = handler117 }118 } else {...

Full Screen

Full Screen

UploadBody.kt

Source:UploadBody.kt Github

copy

Full Screen

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

DefaultBody.kt

Source:DefaultBody.kt Github

copy

Full Screen

...35 * resources). This also means that if an implementation choose to keep it around, `isConsumed` returns false.36 *37 * @return the entire body38 */39 override fun toByteArray(): ByteArray {40 if (isEmpty()) {41 return ByteArray(0)42 }43 return ByteArrayOutputStream(length?.toInt() ?: 32)44 .use { stream ->45 writeTo(stream)46 stream.toByteArray()47 }48 .also { result ->49 openStream = { ByteArrayInputStream(result) }50 calculateLength = { result.size.toLong() }51 }52 }53 /**54 * Returns the body as an [InputStream].55 *56 * @note callers are responsible for closing the returned stream.57 * @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again.58 *59 * @return the body as input stream60 */61 override fun toStream(): InputStream = openStream().buffered().apply {62 // The caller is now responsible for this stream. This make sure that you can't call this twice without handling63 // it. The caller must still call `.close()` on the returned value when done.64 openStream = CONSUMED_STREAM65 }66 /**67 * Writes the body to the [OutputStream].68 *69 * @note callers are responses for closing the [OutputStream].70 * @note implementations may choose to make the [Body] `isConsumed` and can not be written or read from again.71 * @note implementations are recommended to buffer the output stream if they can't ensure bulk writing.72 *73 * @param outputStream [OutputStream] the stream to write to74 * @return [Long] the number of bytes written75 */76 override fun writeTo(outputStream: OutputStream): Long {77 val inputStream = openStream()78 // `copyTo` writes efficiently using a buffer. Reading ensured to be buffered by calling `.buffered`79 return inputStream.buffered()80 .use { it.copyTo(outputStream) }81 .also {82 // The outputStream could be buffered, but we are done reading, so it's time to flush what's left83 outputStream.flush()84 // This prevents implementations from consuming the input stream twice85 openStream = CONSUMED_STREAM86 }87 }88 /**89 * Returns the body emptiness.90 * @return [Boolean] if true, this body is empty91 */92 override fun isEmpty() = openStream === EMPTY_STREAM || (length == 0L)93 /**94 * Returns if the body is consumed.95 * @return [Boolean] if true, `writeTo`, `toStream` and `toByteArray` may throw96 */97 override fun isConsumed() = openStream === CONSUMED_STREAM98 /**99 * Returns the length of the body in bytes100 * @return [Long?] the length in bytes, null if it is unknown101 */102 override val length: Long? by lazy {103 calculateLength?.invoke()?.let {104 if (it == -1L) { null } else { it }105 }106 }107 companion object {108 private val EMPTY_STREAM = {109 ByteArrayInputStream(ByteArray(0))...

Full Screen

Full Screen

Response.kt

Source:Response.kt Github

copy

Full Screen

...24 val contentLength: Long = 0L,25 internal var body: Body = DefaultBody()26) {27 fun body(): Body = body28 val data get() = body.toByteArray()29 /**30 * Get the current values of the header, after normalisation of the header31 * @param header [String] the header name32 * @return the current values (or empty if none)33 */34 operator fun get(header: String): HeaderValues {35 return headers[header]36 }37 fun header(header: String) = get(header)38 override fun toString(): String {39 return buildString {40 appendln("<-- $statusCode $url")41 appendln("Response : $responseMessage")42 appendln("Length : $contentLength")...

Full Screen

Full Screen

Helpers.kt

Source:Helpers.kt Github

copy

Full Screen

...16internal fun mockHttpClient(vararg jsonResponses: JSONObject, code: Int = 200): List<Pair<Future<Request>, Response>> {17 val responses = jsonResponses.map { json ->18 mock<Response> {19 on { statusCode } doReturn code20 on { dataStream } doReturn ByteArrayInputStream(json.toString().toByteArray())21 }22 }23 val requestsAndResponses = responses.map { CompletableFuture<Request>() to it }24 val requestsAndResponsesStack = Stack<Pair<CompletableFuture<Request>, Response>>().apply {25 addAll(requestsAndResponses.asReversed())26 }27 FuelConfiguration(mock {28 on { executeRequest(any()) } doAnswer { answer ->29 val (request, response) = requestsAndResponsesStack.pop()30 request.complete(answer.getArgument(0))31 response32 }33 })34 return requestsAndResponses35}36internal fun Request.bodyContents() = ByteArrayOutputStream().let { outputStream ->37 bodyCallback?.invoke(request, outputStream, 0)38 String(outputStream.toByteArray(), StandardCharsets.UTF_8)39}...

Full Screen

Full Screen

toByteArray

Using AI Code Generation

copy

Full Screen

1val bytes = response.data.toByteArray()2val bytes = response.data.toByteArray()3val bytes = response.data.toByteArray()4val bytes = response.data.toByteArray()5val bytes = response.data.toByteArray()6val bytes = response.data.toByteArray()7val bytes = response.data.toByteArray()8val bytes = response.data.toByteArray()9val bytes = response.data.toByteArray()10val bytes = response.data.toByteArray()11val bytes = response.data.toByteArray()12val bytes = response.data.toByteArray()

Full Screen

Full Screen

toByteArray

Using AI Code Generation

copy

Full Screen

1val testBrayArray = com.github.kittinunf.fuel.core.requests.internml.toByteAethy(response.bodo().asInputStream())d of com.github.kittinunf.fuel.core.requests.internal class2for (i in testByteArray.indices) {3 testString += testByteArray[i].toChar()4}5println(testString)6val bytes = response.data.toByteArray()7val bytes = response.data.toByteArray()8val bytes = response.data.toByteArray()9val bytes = response.data.toByteArray()10val bytes = response.data.toByteArray()11val bytes = response.data.toByteArray()12val bytes = response.data.toByteArray()13val bytes = response.data.toByteArray()14val bytes = response.data.toByteArray()

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