How to use blobs method of com.github.kittinunf.fuel.core.requests.UploadRequest class

Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.UploadRequest.blobs

FuelManager.kt

Source:FuelManager.kt Github

copy

Full Screen

...120        ).request121        return applyOptions(request).download()122    }123    /**124     * Create a [method] [Request] to [path] with [parameters], which can upload blobs and Data Parts125     *126     * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path127     * @param method [Method] the method to upload with, defaults to [Method.POST]128     * @param parameters [Parameters] the optional parameters129     * @return [UploadRequest] the request (extended for upload)130     */131    override fun upload(path: String, method: Method, parameters: Parameters?): UploadRequest {132        val request = Encoding(133            httpMethod = method,134            urlString = path,135            baseUrlString = basePath,136            parameters = if (parameters == null) baseParams else baseParams + parameters137        ).request138        return applyOptions(request).upload()139    }140    fun addRequestInterceptor(interceptor: FoldableRequestInterceptor): FuelManager {141        requestInterceptors += interceptor142        return this143    }144    fun addResponseInterceptor(interceptor: FoldableResponseInterceptor): FuelManager {145        responseInterceptors += interceptor146        return this147    }148    fun removeRequestInterceptor(interceptor: FoldableRequestInterceptor): FuelManager {149        requestInterceptors -= interceptor150        return this151    }152    fun removeResponseInterceptor(interceptor: FoldableResponseInterceptor): FuelManager {153        responseInterceptors -= interceptor154        return this155    }156    fun removeAllRequestInterceptors(): FuelManager {157        requestInterceptors.clear()158        return this159    }160    fun removeAllResponseInterceptors(): FuelManager {161        responseInterceptors.clear()162        return this163    }164    private fun applyOptions(request: Request): Request {165        // Sets base headers ONLY if they are not set166        val unsetBaseHeaders = request.headers.keys.fold(Headers.from(baseHeaders.orEmpty())) {167            result, it -> result.remove(it); result168        }169        return request.header(unsetBaseHeaders).apply {170            executionOptions = RequestExecutionOptions(171                client = client,172                socketFactory = socketFactory,173                hostnameVerifier = hostnameVerifier,174                callbackExecutor = callbackExecutor,175                requestTransformer = requestInterceptors.foldRight({ r: Request -> r }) { f, acc -> f(acc) },176                responseTransformer = responseInterceptors.foldRight({ _: Request, res: Response -> res }) { f, acc -> f(acc) },177                executorService = executorService178            ).also { executor ->179                executor.timeoutInMillisecond = timeoutInMillisecond180                executor.timeoutReadInMillisecond = timeoutReadInMillisecond181                executor.forceMethods = forceMethods182            }183        }184    }185    companion object {186        // manager187        var instance by readWriteLazy { FuelManager() }188        val progressBufferSize: Int get() = instance.progressBufferSize189    }190    /**191     * Create a [Method.GET] [Request] to [path] with [parameters]192     *193     * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path194     * @param parameters [Parameters] the optional parameters195     * @return [Request] the request196     */197    override fun get(path: String, parameters: Parameters?): Request =198        request(Method.GET, path, parameters)199    /**200     * Create a [Method.GET] [Request] to [PathStringConvertible.path] with [parameters]201     *202     * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path203     * @param parameters [Parameters] the optional parameters204     * @return [Request] the request205     */206    override fun get(convertible: PathStringConvertible, parameters: Parameters?): Request =207        request(Method.GET, convertible, parameters)208    /**209     * Create a [Method.POST] [Request] to [path] with [parameters]210     *211     * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path212     * @param parameters [Parameters] the optional parameters213     * @return [Request] the request214     */215    override fun post(path: String, parameters: Parameters?): Request =216        request(Method.POST, path, parameters)217    /**218     * Create a [Method.POST] [Request] to [PathStringConvertible.path] with [parameters]219     *220     * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path221     * @param parameters [Parameters] the optional parameters222     * @return [Request] the request223     */224    override fun post(convertible: PathStringConvertible, parameters: Parameters?): Request =225        request(Method.POST, convertible, parameters)226    /**227     * Create a [Method.PUT] [Request] to [path] with [parameters]228     *229     * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path230     * @param parameters [Parameters] the optional parameters231     * @return [Request] the request232     */233    override fun put(path: String, parameters: Parameters?): Request =234        request(Method.PUT, path, parameters)235    /**236     * Create a [Method.PUT] [Request] to [PathStringConvertible.path] with [parameters]237     *238     * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path239     * @param parameters [Parameters] the optional parameters240     * @return [Request] the request241     */242    override fun put(convertible: PathStringConvertible, parameters: Parameters?): Request =243        request(Method.PUT, convertible, parameters)244    /**245     * Create a [Method.PATCH] [Request] to [path] with [parameters]246     *247     * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path248     * @param parameters [Parameters] the optional parameters249     * @return [Request] the request250     */251    override fun patch(path: String, parameters: Parameters?): Request =252        request(Method.PATCH, path, parameters)253    /**254     * Create a [Method.PATCH] [Request] to [PathStringConvertible.path] with [parameters]255     *256     * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path257     * @param parameters [Parameters] the optional parameters258     * @return [Request] the request259     */260    override fun patch(convertible: PathStringConvertible, parameters: Parameters?): Request =261        request(Method.PATCH, convertible, parameters)262    /**263     * Create a [Method.DELETE] [Request] to [path] with [parameters]264     *265     * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path266     * @param parameters [Parameters] the optional parameters267     * @return [Request] the request268     */269    override fun delete(path: String, parameters: Parameters?): Request =270        request(Method.DELETE, path, parameters)271    /**272     * Create a [Method.DELETE] [Request] to [PathStringConvertible.path] with [parameters]273     *274     * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path275     * @param parameters [Parameters] the optional parameters276     * @return [Request] the request277     */278    override fun delete(convertible: PathStringConvertible, parameters: Parameters?): Request =279        request(Method.DELETE, convertible, parameters)280    /**281     * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can download to a file282     *283     * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path284     * @param method [Method] the method to download with, defaults to [Method.GET]285     * @param parameters [Parameters] the optional parameters286     * @return [DownloadRequest] the request (extended for download)287     */288    override fun download(convertible: PathStringConvertible, method: Method, parameters: Parameters?): DownloadRequest =289        download(convertible.path, method, parameters)290    /**291     * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can upload blobs and292     * Data Parts293     *294     * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path295     * @param method [Method] the method to upload with, defaults to [Method.POST]296     * @param parameters [Parameters] the optional parameters297     * @return [UploadRequest] the request (extended for upload)298     */299    override fun upload(convertible: PathStringConvertible, method: Method, parameters: Parameters?): UploadRequest =300        upload(convertible.path, method, parameters)301    /**302     * Create a [Method.HEAD] [Request] to [path] with [parameters]303     *304     * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path305     * @param parameters [Parameters] the optional parameters...

Full Screen

Full Screen

RequestFactory.kt

Source:RequestFactory.kt Github

copy

Full Screen

...67         * @return [DownloadRequest] the request (extended for download)68         */69        fun download(convertible: PathStringConvertible, method: Method = Method.GET, parameters: Parameters? = null): DownloadRequest70        /**71         * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can upload blobs and72         * Data Parts73         *74         * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path75         * @param method [Method] the method to upload with, defaults to [Method.POST]76         * @param parameters [Parameters] the optional parameters77         * @return [UploadRequest] the request (extended for upload)78         */79        fun upload(convertible: PathStringConvertible, method: Method = Method.POST, parameters: Parameters? = null): UploadRequest80        /**81         * Create a [method] [Request] to [path] with [parameters], which can upload blobs and Data Parts82         *83         * @parameters path [String] the absolute or relative to [FuelManager.instance]' base-path path84         * @parameters method [Method] the method to upload with, defaults to [Method.POST]85         * @parameters parameters [Parameters] the optional parameters86         * @return [UploadRequest] the request (extended for upload)87         */88        fun upload(path: String, method: Method = Method.POST, parameters: Parameters? = null): UploadRequest89        /**90         * Create a [Method.GET] [Request] to [path] with [parameters]91         *92         * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path93         * @param parameters [Parameters] the optional parameters94         * @return [Request] the request95         */...

Full Screen

Full Screen

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

UploadRequest.kt

Source:UploadRequest.kt Github

copy

Full Screen

...80                    .apply { this.ensureBoundary() }81            } as UploadRequest82    }83    @Deprecated("Use request.add({ BlobDataPart(...) }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)84    fun blobs(@Suppress("DEPRECATION") blobsCallback: (Request, URL) -> Iterable<Blob>): UploadRequest =85        throw NotImplementedError("request.blobs has been removed. Use request.add({ BlobDataPart(...) }, { ... }, ...) instead.")86    @Deprecated("Use request.add { BlobDataPart(...) } instead", ReplaceWith("add(blobsCallback)"))87    fun blob(@Suppress("DEPRECATION") blobCallback: (Request, URL) -> Blob): UploadRequest =88        throw NotImplementedError("request.blob has been removed. Use request.add { BlobDataPart(...) } instead.")89    @Deprecated("Use request.add({ ... }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)90    fun dataParts(dataPartsCallback: (Request, URL) -> Iterable<DataPart>): UploadRequest =91        throw NotImplementedError("request.dataParts has been removed. Use request.add { XXXDataPart(...) } instead.")92    @Deprecated("Use request.add({ FileDataPart(...) }, { ... }, ...) instead", ReplaceWith(""), DeprecationLevel.ERROR)93    fun sources(sourcesCallback: (Request, URL) -> Iterable<File>): UploadRequest =94        throw NotImplementedError("request.sources has been removed. Use request.add({ BlobDataPart(...) }, { ... }, ...) instead.")95    @Deprecated("Use request.add { FileDataPart(...)} instead", ReplaceWith("add(sourceCallback)"), DeprecationLevel.ERROR)96    fun source(sourceCallback: (Request, URL) -> File): UploadRequest =97        throw NotImplementedError("request.source has been removed. Use request.add { FileDataPart(...) } instead.")98    @Deprecated("Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead", ReplaceWith(""), DeprecationLevel.ERROR)99    fun name(nameCallback: () -> String): UploadRequest =100        throw NotImplementedError("request.name has been removed. Set the name via DataPart (FileDataPart, InlineDataPart, BlobDataPart) instead")...

Full Screen

Full Screen

blobs

Using AI Code Generation

copy

Full Screen

1val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result2val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result3val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result4val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result5val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result6val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result7val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result8val imageFile = File("path/to/image/file") val (request, response, result) = Fuel.upload("/upload/image") .blob(imageFile) .response() val (data, error) = result

Full Screen

Full Screen

blobs

Using AI Code Generation

copy

Full Screen

1val file = File("/Users/kittinunf/Downloads/IMG_20161023_153139.jpg")2val uploadFileRequest = uploadRequest.source { request, url ->3file.inputStream()4}5val (request, response, result) = uploadFileRequest.response()6println(request)7println(response)8println(result)9val file = File("/Users/kittinunf/Downloads/IMG_20161023_153139.jpg")10val uploadFileRequest = uploadRequest.source { request, url ->11file.inputStream()12}13val (request, response, result) = uploadFileRequest.response()14println(request)15println(response)16println(result)17val file = File("/Users/kittinunf/Downloads/IMG_20161023_153139.jpg")18val uploadFileRequest = uploadRequest.source { request, url ->19file.inputStream()20}21val (request, response, result) = uploadFileRequest.response()22println(request)23println(response)24println(result)25val file = File("/Users/kittinunf/Downloads/IMG_20161023_153139.jpg")26val uploadFileRequest = uploadRequest.source { request, url ->27file.inputStream()28}29val (request, response, result) = uploadFileRequest.response()30println(request)31println(response)32println(result)33val file = File("/Users/kittinunf/Downloads/IMG_20161023_153139.jpg")34val uploadFileRequest = uploadRequest.source { request, url ->35file.inputStream()36}37val (request, response, result) = uploadFileRequest.response()38println(request)39println(response)40println(result)

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.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful