Best Fuel code snippet using com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer
DefaultRequest.kt
Source:DefaultRequest.kt  
...17import com.github.kittinunf.fuel.core.ResponseResultHandler18import com.github.kittinunf.fuel.core.ResponseValidator19import com.github.kittinunf.fuel.core.ResultHandler20import com.github.kittinunf.fuel.core.Tags21import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer22import com.github.kittinunf.fuel.core.deserializers.StringDeserializer23import com.github.kittinunf.fuel.core.response24import java.io.ByteArrayInputStream25import java.io.File26import java.io.FileInputStream27import java.io.InputStream28import java.net.URL29import java.net.URLConnection30import java.nio.charset.Charset31import kotlin.reflect.KClass32data class DefaultRequest(33    override val method: Method,34    override var url: URL,35    override val headers: Headers = Headers(),36    override var parameters: Parameters = listOf(),37    internal var _body: Body = DefaultBody(),38    override val enabledFeatures: RequestFeatures = mutableMapOf(),39    private val tags: Tags = mutableMapOf()40) : Request {41    override lateinit var executionOptions: RequestExecutionOptions42    override val body: Body get() = _body43    /**44     * Get the current values of the header, after normalisation of the header45     * @param header [String] the header name46     * @return the current values (or empty if none)47     */48    override operator fun get(header: String): HeaderValues {49        return headers[header]50    }51    /**52     * Set the values of the header, overriding what's there, after normalisation of the header53     *54     * @param header [String] the header name55     * @param values [Collection<*>] the values to be transformed through #toString56     * @return self57     */58    override operator fun set(header: String, values: Collection<*>): Request {59        headers[header] = values.map { it.toString() }60        return request61    }62    /**63     * Set the value of the header, overriding what's there, after normalisation of the header64     *65     * @param header [String] the header name66     * @param value [Any] the value to be transformed through #toString67     */68    override operator fun set(header: String, value: Any): Request {69        when (value) {70            is Collection<*> -> this[header] = value71            else -> headers[header] = value.toString()72        }73        return request74    }75    /**76     * Get the current values77     *78     * @see get(header: String)79     * @return [HeaderValues] the current values80     */81    override fun header(header: String) = get(header)82    /**83     * Replace the headers with the map provided84     *85     * @note In earlier versions the mapOf variant of this function worked differently than the vararg pairs variant,86     *  which has been changed to make any call to header(...) always overwrite the values and any call to87     *  appendHeader(...) will try to append the value.88     *89     * @see set(header: String, values: Collection<*>)90     * @see set(header: String, value: Any)91     *92     * @param map [Map<String, Any>] map of headers to replace. Value can be a list or single value93     * @return [Request] the modified request94     */95    override fun header(map: Map<String, Any>): Request {96        headers.putAll(Headers.from(map))97        return request98    }99    /**100     * Replace the headers with the pairs provided101     *102     * @note In earlier versions the mapOf variant of this function worked differently than the vararg pairs variant,103     *  which has been changed to make any call to header(...) always overwrite the values and any call to104     *  appendHeader(...) will try to append the value.105     *106     * @see set(header: String, values: Collection<*>)107     * @see set(header: String, value: Any)108     *109     * @param pairs [Pair<String, Any>] map of headers to replace. Value can be a list or single value110     * @return [Request] the modified request111     */112    override fun header(vararg pairs: Pair<String, Any>): Request {113        headers.putAll(Headers.from(*pairs))114        return request115    }116    /**117     * Replace the header with the provided values118     *119     * @see set(header: String, values: Collection<*>)120     *121     * @param header [String] the header to set122     * @param values [List<Any>] the values to set the header to123     * @return [Request] the modified request124     */125    override fun header(header: String, values: Collection<*>) = set(header, values)126    /**127     * Replace the header with the provided value128     *129     * @see set(header: String, values: List<Any>)130     *131     * @param header [String] the header to set132     * @param value [Any] the value to set the header to133     * @return [Request] the modified request134     */135    override fun header(header: String, value: Any): Request = set(header, value)136    /**137     * Replace the header with the provided values138     *139     * @see set(header: String, values: List<Any>)140     *141     * @param header [String] the header to set142     * @param values [Any] the values to set the header to143     * @return [Request] the modified request144     */145    override fun header(header: String, vararg values: Any) = set(header, values.toList())146    /**147     * Appends the value to the header or sets it if there was none yet148     *149     * @param header [String] the header name to append to150     * @param value [Any] the value to be transformed through #toString151     */152    override fun appendHeader(header: String, value: Any): Request {153        headers.append(header, value)154        return request155    }156    /**157     * Appends the value to the header or sets it if there was none yet158     *159     * @param header [String] the header name to append to160     * @param values [Any] the value to be transformed through #toString161     */162    override fun appendHeader(header: String, vararg values: Any): Request {163        headers.append(header, values.toList())164        return request165    }166    /**167     * Append each pair, using the key as header name and value as header content168     *169     * @param pairs [Pair<String, Any>]170     */171    override fun appendHeader(vararg pairs: Pair<String, Any>): Request {172        pairs.forEach { pair -> appendHeader(pair.first, pair.second) }173        return request174    }175    /**176     * Sets the body to be read from a generic body source.177     *178     * @note in earlier versions the body callback would be called multiple times in order to maybe get the size. But179     *  that would lead to closed streams being unable to be read. If the size is known, set it before anything else.180     *181     * @param openStream [BodySource] a function that yields a stream182     * @param calculateLength [Number?] size in +bytes+ if it is known183     * @param charset [Charset] the charset to write with184     * @param repeatable [Boolean] loads the body into memory upon reading185     *186     * @return [Request] the request187     */188    override fun body(openStream: BodySource, calculateLength: BodyLength?, charset: Charset, repeatable: Boolean): Request {189        _body = DefaultBody190            .from(openStream = openStream, calculateLength = calculateLength, charset = charset)191            .let { body -> if (repeatable) body.asRepeatable() else body }192        return request193    }194    /**195     * Sets the body from a generic stream196     *197     * @note the stream will be read from the position it's at. Make sure you rewind it if you want it to be read from198     *  the start.199     *200     * @param stream [InputStream] a stream to read from201     * @param calculateLength [Number?] size in bytes if it is known202     * @param charset [Charset] the charset to write with203     * @param repeatable [Boolean] loads the body into memory upon reading204     *205     * @return [Request] the request206     */207    override fun body(stream: InputStream, calculateLength: BodyLength?, charset: Charset, repeatable: Boolean) =208        body(openStream = { stream }, calculateLength = calculateLength, charset = charset, repeatable = repeatable)209    /**210     * Sets the body from a byte array211     *212     * @param bytes [ByteArray] the bytes to write213     * @param charset [Charset] the charset to write with214     * @return [Request] the request215     */216    override fun body(bytes: ByteArray, charset: Charset) =217        body(stream = ByteArrayInputStream(bytes), calculateLength = { bytes.size.toLong() }, charset = charset, repeatable = true)218    /**219     * Sets the body from a string220     *221     * @param body [String] the string to write222     * @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.241     *242     * @param file [File] the file to write to the body243     * @param charset [Charset] the charset to write with244     * @return [Request] the request245     */246    override fun body(file: File, charset: Charset): Request = when (charset) {247        Charsets.UTF_8 -> body({ FileInputStream(file) }, { file.length() }, charset)248        else -> body({ FileInputStream(file) }, null, charset)249    }.let {250        if (header(Headers.CONTENT_TYPE).lastOrNull().isNullOrBlank()) {251            val contentType = URLConnection.guessContentTypeFromName(file.name)252            header(Headers.CONTENT_TYPE, "$contentType; charset=${charset.name()}")253        } else {254            it255        }256    }257    /**258     * Sets the body to a defined [Body]259     *260     * @param body [Body] the body to assign261     * @return [Request] the request262     */263    override fun body(body: Body): Request {264        _body = body265        return request266    }267    /**268     * Add a [ProgressCallback] tracking the [Body] of the [Request]269     *270     * @see body271     * @see com.github.kittinunf.fuel.core.requests.UploadRequest.progress272     *273     * @return self274     */275    override fun requestProgress(handler: ProgressCallback): Request {276        executionOptions.requestProgress += handler277        return request278    }279    /**280     * Add a [ProgressCallback] tracking the [Body] of the [com.github.kittinunf.fuel.core.Response]281     *282     * @see com.github.kittinunf.fuel.core.requests.DownloadRequest.progress283     *284     * @return self285     */286    override fun responseProgress(handler: ProgressCallback): Request {287        executionOptions.responseProgress += handler288        return request289    }290    /**291     * Add a [InterruptCallback] to the [RequestExecutionOptions]292     *293     * @see RequestExecutionOptions.interruptCallbacks294     *295     * @return self296     */297    override fun interrupt(interrupt: InterruptCallback) = request.also {298        it.executionOptions.interruptCallbacks.plusAssign(interrupt)299    }300    /**301     * Overwrite the [Request] [timeout] in milliseconds302     *303     * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour304     * @note the default client sets [java.net.HttpURLConnection.setConnectTimeout]305     *306     * @param timeout [Int] timeout in milliseconds307     * @return self308     */309    override fun timeout(timeout: Int) = request.also {310        it.executionOptions.timeoutInMillisecond = timeout311    }312    /**313     * Overwrite the [Request] [timeout] in milliseconds314     *315     * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour316     * @note the default client sets [java.net.HttpURLConnection.setReadTimeout]317     *318     * @param timeout [Int] timeout in milliseconds319     * @return self320     */321    override fun timeoutRead(timeout: Int) = request.also {322        it.executionOptions.timeoutReadInMillisecond = timeout323    }324    /**325     * Follow redirects as handled by instances of RedirectInterceptors326     *  i.e. [com.github.kittinunf.fuel.core.interceptors.redirectResponseInterceptor]327     *328     * @note The interceptor must implement this behaviour329     * @note The provided RedirectResponseInterceptor defaults to true330     *331     * @param allowRedirects [Boolean] true if allowing, false if not332     * @return self333     */334    override fun allowRedirects(allowRedirects: Boolean) = request.also {335        it.executionOptions.allowRedirects = allowRedirects336    }337    /**338     * Overwrite [RequestExecutionOptions] http cache usage flag339     *340     * @note [com.github.kittinunf.fuel.core.Client] must implement this behaviour341     * @note The default client sends `Cache-Control: none` if this flag is false, defaults to true342     *343     * @see java.net.HttpURLConnection.setUseCaches344     * @param useHttpCache [Boolean] true if suggest client to allow cached responses, false otherwise345     */346    override fun useHttpCache(useHttpCache: Boolean) = request.also {347        it.executionOptions.useHttpCache = useHttpCache348    }349    /**350     * Overwrite [RequestExecutionOptions] response validator block351     *352     * @note The default responseValidator is to throw [com.github.kittinunf.fuel.core.HttpException]353     * @note if the response http status code is not in the range of (100 - 399) which should consider as failure response354     *355     * @param validator [ResponseValidator]356     * @return [Request] the modified request357     */358    override fun validate(validator: ResponseValidator) = request.also {359        it.executionOptions.responseValidator = validator360    }361    /**362     * Attach tag to the request363     *364     * @note tag is a generic purpose tagging for Request. This can be used to attach arbitrarily object to the Request instance.365     * @note Tags internally is represented as hashMap that uses class as a key.366     *367     * @param t [Any]368     * @return [Request] the modified request369     */370    override fun tag(t: Any) = request.also {371        tags[t::class] = t372    }373    /**374     * Return corresponding tag from the request375     *376     * @note tag is a generic purpose tagging for Request. This can be used to attach arbitrarily object to the Request instance.377     * @note Tags internally is represented as hashMap that uses class as a key.378     *379     * @param clazz [KClass]380     * @return [Any] previously attached tag if any, null otherwise381     */382    override fun <T : Any> getTag(clazz: KClass<T>) = tags[clazz] as? T383    override val request: Request get() = this384    /**385     * Returns a string representation of the request.386     *387     * @see com.github.kittinunf.fuel.core.extensions.httpString388     * @see com.github.kittinunf.fuel.core.extensions.cUrlString389     *390     * @return [String] the string representation391     */392    override fun toString(): String = buildString {393        appendln("--> $method $url")394        appendln("Body : ${body.asString(header(Headers.CONTENT_TYPE).lastOrNull())}")395        appendln("Headers : (${headers.size})")396        val appendHeaderWithValue = { key: String, value: String -> appendln("$key : $value") }397        headers.transformIterate(appendHeaderWithValue)398    }399    override fun response(handler: ResponseResultHandler<ByteArray>) =400        response(ByteArrayDeserializer(), handler)401    override fun response(handler: ResultHandler<ByteArray>) =402        response(ByteArrayDeserializer(), handler)403    override fun response(handler: ResponseHandler<ByteArray>) =404        response(ByteArrayDeserializer(), handler)405    override fun response(handler: Handler<ByteArray>) =406        response(ByteArrayDeserializer(), handler)407    override fun response() =408        response(ByteArrayDeserializer())409    override fun responseString(charset: Charset, handler: ResponseResultHandler<String>) =410        response(StringDeserializer(charset), handler)411    override fun responseString(handler: ResponseResultHandler<String>) =412        responseString(Charsets.UTF_8, handler)413    override fun responseString(charset: Charset, handler: ResultHandler<String>) =414        response(StringDeserializer(charset), handler)415    override fun responseString(handler: ResultHandler<String>) =416        responseString(Charsets.UTF_8, handler)417    override fun responseString(charset: Charset, handler: ResponseHandler<String>) =418        response(StringDeserializer(charset), handler)419    override fun responseString(handler: ResponseHandler<String>) =420        response(StringDeserializer(), handler)421    override fun responseString(charset: Charset, handler: Handler<String>) =422        response(StringDeserializer(charset), handler)...Coroutines.kt
Source:Coroutines.kt  
...8import com.github.kittinunf.fuel.core.await9import com.github.kittinunf.fuel.core.awaitResponse10import com.github.kittinunf.fuel.core.awaitResponseResult11import com.github.kittinunf.fuel.core.awaitResult12import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer13import com.github.kittinunf.fuel.core.deserializers.EmptyDeserializer14import com.github.kittinunf.fuel.core.deserializers.StringDeserializer15import com.github.kittinunf.result.Result16import kotlinx.coroutines.Dispatchers17import kotlinx.coroutines.withContext18import java.nio.charset.Charset19import kotlin.coroutines.CoroutineContext20/**21 * Await the [T] using a [scope], defaulting to [Dispatchers.IO]22 *23 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown24 *25 * @param deserializable [U] the instance that can turn the Response into a [T]26 * @param scope [CoroutineContext] the context to run within27 *28 * @return [T]29 */30@Throws31suspend inline fun <T : Any, U : Deserializable<T>> Request.await(deserializable: U, scope: CoroutineContext = Dispatchers.IO): T =32    withContext(scope) { await(deserializable) }33/**34 * Await the task finish without getting result using a [scope], defaulting to [Dispatchers.IO]35 *36 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown37 *38 * @param scope [CoroutineContext] the context to run within39 */40@Throws41suspend fun Request.awaitUnit(scope: CoroutineContext = Dispatchers.IO): Unit = await(EmptyDeserializer, scope)42/**43 * Await the [T] using a [scope], defaulting to [Dispatchers.IO], wrapped in [Result]44 *45 * @param deserializable [U] the instance that can turn the Response into a [T]46 * @param scope [CoroutineContext] the context to run within47 *48 * @return [Result] [T] or [FuelError]49 */50suspend inline fun <T : Any, U : Deserializable<T>> Request.awaitResult(deserializable: U, scope: CoroutineContext = Dispatchers.IO): Result<T, FuelError> =51    withContext(scope) { awaitResult(deserializable) }52/**53 * Await the [T] using a [scope], defaulting to [Dispatchers.IO], including metadata54 *55 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown56 *57 * @param deserializable [U] the instance that can turn the Response into a [T]58 * @param scope [CoroutineContext] the context to run within59 *60 * @return [ResponseOf] [T]61 */62@Throws63suspend inline fun <T : Any, U : Deserializable<T>> Request.awaitResponse(deserializable: U, scope: CoroutineContext = Dispatchers.IO): ResponseOf<T> =64    withContext(scope) { awaitResponse(deserializable) }65/**66 * Await the [T] using a [scope], defaulting to [Dispatchers.IO], wrapped in [Result], including metadata67 *68 * @param deserializable [U] the instance that can turn the Response into a [T]69 * @param scope [CoroutineContext] the context to run within70 *71 * @return [ResponseResultOf] [T] or [FuelError]72 */73suspend inline fun <T : Any, U : Deserializable<T>> Request.awaitResponseResult(deserializable: U, scope: CoroutineContext = Dispatchers.IO): ResponseResultOf<T> =74    withContext(scope) { awaitResponseResult(deserializable) }75/***76 * Awaits the response as a [ByteArray] with [scope] as context77 *78 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown79 *80 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]81 * @return [ByteArray] if no exceptions are thrown82 */83@Throws84suspend inline fun Request.awaitByteArray(scope: CoroutineContext = Dispatchers.IO): ByteArray =85    await(ByteArrayDeserializer(), scope)86/***87 * Awaits the response as a [ByteArray] with [scope] as context, with metadata88 *89 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown90 *91 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]92 * @return [ResponseOf] [ByteArray] if no exceptions are thrown93 */94@Throws95suspend inline fun Request.awaitByteArrayResponse(scope: CoroutineContext = Dispatchers.IO): ResponseOf<ByteArray> =96    awaitResponse(ByteArrayDeserializer(), scope)97/***98 * Awaits the response as a [String] with [scope] as context99 *100 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown101 *102 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]103 * @param charset [Charset] the charset to use for the [String], defaulting to [Charsets.UTF_8]104 *105 * @return [String] if no exceptions are thrown106 */107@Throws108suspend inline fun Request.awaitString(charset: Charset = Charsets.UTF_8, scope: CoroutineContext = Dispatchers.IO): String =109    await(StringDeserializer(charset), scope)110/***111 * Awaits the response as a [String] with [scope] as context, with metadata112 *113 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]114 * @param charset [Charset] the charset to use for the [String], defaulting to [Charsets.UTF_8]115 * @return [ResponseOf] [String] if no exceptions are thrown116 */117@Throws118suspend inline fun Request.awaitStringResponse(charset: Charset = Charsets.UTF_8, scope: CoroutineContext = Dispatchers.IO): ResponseOf<String> =119    awaitResponse(StringDeserializer(charset), scope)120/***121 * Awaits the response as a [U] with [scope] as context122 *123 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown124 *125 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]126 * @param deserializable [ResponseDeserializable] instance that can turn the response into a [U]127 *128 * @return [U] if no exceptions are thrown129 */130@Throws131suspend inline fun <U : Any> Request.awaitObject(deserializable: ResponseDeserializable<U>, scope: CoroutineContext = Dispatchers.IO): U =132    await(deserializable, scope)133/***134 * Awaits the response as a [U] with [scope] as context, with metadata135 *136 * @throws FuelError if deserialization fails, if network fails, other internal exception is thrown137 *138 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]139 * @param deserializable [ResponseDeserializable] instance that can turn the response into a [U]140 *141 * @return [ResponseOf] [U] if no exceptions are thrown142 */143@Throws144suspend inline fun <U : Any> Request.awaitObjectResponse(deserializable: ResponseDeserializable<U>, scope: CoroutineContext = Dispatchers.IO): ResponseOf<U> =145    awaitResponse(deserializable, scope)146/***147 * Awaits the response as a [ByteArray] with [scope] as context148 *149 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]150 * @return [Result] [ByteArray] or [FuelError]151 */152suspend inline fun Request.awaitByteArrayResult(scope: CoroutineContext = Dispatchers.IO): Result<ByteArray, FuelError> =153    awaitResult(ByteArrayDeserializer(), scope)154/***155 * Awaits the response as a [ByteArray] with [scope] as context, with metadata156 *157 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]158 * @return [ResponseResultOf] [ByteArray]159 */160suspend inline fun Request.awaitByteArrayResponseResult(scope: CoroutineContext = Dispatchers.IO): ResponseResultOf<ByteArray> =161    awaitResponseResult(ByteArrayDeserializer(), scope)162/***163 * Awaits the response as a [String] with [scope] as context164 *165 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]166 * @param charset [Charset] the charset to use for the [String], defaulting to [Charsets.UTF_8]167 *168 * @return [Result] [String] or [FuelError]169 */170suspend inline fun Request.awaitStringResult(charset: Charset = Charsets.UTF_8, scope: CoroutineContext = Dispatchers.IO): Result<String, FuelError> =171    awaitResult(StringDeserializer(charset), scope)172/***173 * Awaits the response as a [String] with [scope] as context, with metadata174 *175 * @param scope [CoroutineContext] the coroutine context you want the call to be made on, defaulting to [Dispatchers.IO]...Request.kt
Source:Request.kt  
1package com.github.kittinunf.fuel.core2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer4import com.github.kittinunf.fuel.core.deserializers.StringDeserializer5import com.github.kittinunf.fuel.core.requests.DownloadTaskRequest6import com.github.kittinunf.fuel.core.requests.TaskRequest7import com.github.kittinunf.fuel.core.requests.UploadTaskRequest8import com.github.kittinunf.fuel.util.Base649import com.github.kittinunf.result.Result10import java.io.ByteArrayOutputStream11import java.io.File12import java.io.OutputStream13import java.net.URL14import java.nio.charset.Charset15import java.util.concurrent.Callable16import java.util.concurrent.Executor17import java.util.concurrent.ExecutorService18import java.util.concurrent.Future19import javax.net.ssl.HostnameVerifier20import javax.net.ssl.SSLSocketFactory21class Request : Fuel.RequestConvertible {22    enum class Type {23        REQUEST,24        DOWNLOAD,25        UPLOAD26    }27    var timeoutInMillisecond = 1500028    var timeoutReadInMillisecond = timeoutInMillisecond29    var type: Type = Type.REQUEST30    lateinit var httpMethod: Method31    lateinit var path: String32    lateinit var url: URL33    //body34    var bodyCallback: ((Request, OutputStream?, Long) -> Long)? = null35    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 {119            throw IllegalStateException("progress is only used with RequestType.DOWNLOAD or RequestType.UPLOAD")120        }121        return this122    }123    fun dataParts(dataParts: (Request, URL) -> Iterable<DataPart>): Request {124        val uploadTaskRequest = taskRequest as? UploadTaskRequest ?: throw IllegalStateException("source is only used with RequestType.UPLOAD")125        val parts = dataParts.invoke(request, request.url)126        mediaTypes.apply {127            clear()128            addAll(parts.map { it.type })129        }130        names.apply {131            clear()132            addAll(parts.map { it.name })133        }134        uploadTaskRequest.apply {135            sourceCallback = { _, _ -> parts.map { it.file } }136        }137        return this138    }139    fun sources(sources: (Request, URL) -> Iterable<File>): Request {140        mediaTypes.clear()141        names.clear()142        val uploadTaskRequest = taskRequest as? UploadTaskRequest ?: throw IllegalStateException("source is only used with RequestType.UPLOAD")143        uploadTaskRequest.apply {144            sourceCallback = sources145        }146        return this147    }148    fun source(source: (Request, URL) -> File): Request {149        sources { request, _ ->150            listOf(source.invoke(request, request.url))151        }152        return this153    }154    fun name(name: () -> String): Request {155        this.name = name()156        return this157    }158    fun destination(destination: (Response, URL) -> File): Request {159        val downloadTaskRequest = taskRequest as? DownloadTaskRequest ?: throw IllegalStateException("destination is only used with RequestType.DOWNLOAD")160        downloadTaskRequest.apply {161            destinationCallback = destination162        }163        return this164    }165    fun interrupt(interrupt: (Request) -> Unit): Request {166        taskRequest.apply {167            interruptCallback = interrupt168        }169        return this170    }171    fun submit(callable: Callable<*>) {172        taskFuture = executor.submit(callable)173    }174    fun callback(f: () -> Unit) {175        callbackExecutor.execute {176            f.invoke()177        }178    }179    fun cancel() {180        taskFuture?.cancel(true)181    }182    override val request: Request183        get() = this184    fun cUrlString(): String {185        val elements = mutableListOf("$ curl -i")186        //method187        if (httpMethod != Method.GET) {188            elements.add("-X $httpMethod")189        }190        //body191        val escapedBody = String(httpBody).replace("\"", "\\\"")192        if (escapedBody.isNotEmpty()) {193            elements.add("-d \"$escapedBody\"")194        }195        //headers196        for ((key, value) in httpHeaders) {197            elements.add("-H \"$key:$value\"")198        }199        //url200        elements.add("\"$url\"")201        return elements.joinToString(" ")202    }203    override fun toString(): String {204        val elements = mutableListOf("--> $httpMethod ($url)")205        //body206        elements.add("Body : ${if (httpBody.isNotEmpty()) String(httpBody) else "(empty)"}")207        //headers208        elements.add("Headers : (${httpHeaders.size})")209        for ((key, value) in httpHeaders) {210            elements.add("$key : $value")211        }212        return elements.joinToString("\n")213    }214    //byte array215    fun response(handler: (Request, Response, Result<ByteArray, FuelError>) -> Unit) =216            response(byteArrayDeserializer(), handler)217    fun response(handler: Handler<ByteArray>) = response(byteArrayDeserializer(), handler)218    fun response() = response(byteArrayDeserializer())219    //string220    fun responseString(charset: Charset = Charsets.UTF_8, handler: (Request, Response, Result<String, FuelError>) -> Unit) =221            response(stringDeserializer(charset), handler)222    fun responseString(charset: Charset, handler: Handler<String>) = response(stringDeserializer(charset), handler)223    fun responseString(handler: Handler<String>) = response(stringDeserializer(), handler)224    @JvmOverloads225    fun responseString(charset: Charset = Charsets.UTF_8) = response(stringDeserializer(charset))226    //object227    fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>, handler: (Request, Response, Result<T, FuelError>) -> Unit) = response(deserializer, handler)228    fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>, handler: Handler<T>) = response(deserializer, handler)229    fun <T : Any> responseObject(deserializer: ResponseDeserializable<T>) = response(deserializer)230    companion object {231        fun byteArrayDeserializer() = ByteArrayDeserializer()232        fun stringDeserializer(charset: Charset = Charsets.UTF_8) = StringDeserializer(charset)233    }234}...Reactor.kt
Source:Reactor.kt  
2import com.github.kittinunf.fuel.core.Deserializable3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer7import com.github.kittinunf.fuel.core.deserializers.EmptyDeserializer8import com.github.kittinunf.fuel.core.deserializers.StringDeserializer9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.core.response11import com.github.kittinunf.result.Result12import reactor.core.publisher.Mono13import reactor.core.publisher.MonoSink14import java.nio.charset.Charset15private fun <T : Any> Request.monoResult(async: Request.(MonoSink<T>) -> CancellableRequest): Mono<T> =16    Mono.create<T> { sink ->17        val cancellableRequest = async(sink)18        sink.onCancel { cancellableRequest.cancel() }19    }20private fun <T : Any> Request.monoResultFold(mapper: Deserializable<T>): Mono<T> =21    monoResult { sink ->22        response(mapper) { _, _, result ->23            result.fold(sink::success, sink::error)24        }25    }26private fun <T : Any> Request.monoResultUnFolded(mapper: Deserializable<T>): Mono<Result<T, FuelError>> =27    monoResult { sink ->28        response(mapper) { _, _, result ->29            sink.success(result)30        }31    }32/**33 * Get a single [Response]34 * @return [Mono<Response>] the [Mono]35 */36fun Request.monoResponse(): Mono<Response> =37    monoResult { sink ->38        response { _, res, _ -> sink.success(res) }39    }40/**41 * Get a single [ByteArray] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]42 *43 * @see monoResultBytes44 * @return [Mono<ByteArray>] the [Mono]45 */46fun Request.monoBytes(): Mono<ByteArray> = monoResultFold(ByteArrayDeserializer())47/**48 * Get a single [String] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]49 *50 * @see monoResultString51 *52 * @param charset [Charset] the charset to use for the string, defaults to [Charsets.UTF_8]53 * @return [Mono<String>] the [Mono]54 */55fun Request.monoString(charset: Charset = Charsets.UTF_8): Mono<String> = monoResultFold(StringDeserializer(charset))56/**57 * Get a single [T] via a [MonoSink.success], or any [FuelError] via [MonoSink.error]58 *59 * @see monoResultObject60 *61 * @param mapper [Deserializable<T>] the deserializable that can turn the response int a [T]62 * @return [Mono<T>] the [Mono]63 */64fun <T : Any> Request.monoObject(mapper: Deserializable<T>): Mono<T> = monoResultFold(mapper)65/**66 * Get a single [ByteArray] or [FuelError] via [Result]67 *68 * @see monoBytes69 * @return [Mono<Result<ByteArray, FuelError>>] the [Mono]70 */71fun Request.monoResultBytes(): Mono<Result<ByteArray, FuelError>> =72    monoResultUnFolded(ByteArrayDeserializer())73/**74 * Get a single [String] or [FuelError] via [Result]75 *76 * @see monoString77 *78 * @param charset [Charset] the charset to use for the string, defaults to [Charsets.UTF_8]79 * @return [Mono<Result<ByteArray, FuelError>>] the [Mono]80 */81fun Request.monoResultString(charset: Charset = Charsets.UTF_8): Mono<Result<String, FuelError>> =82    monoResultUnFolded(StringDeserializer(charset))83/**84 * Get a single [T] or [FuelError] via [Result]85 *86 * @see monoObject...FuelLiveData.kt
Source:FuelLiveData.kt  
...4import com.github.kittinunf.fuel.core.Deserializable5import com.github.kittinunf.fuel.core.FuelError6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.Response8import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer9import com.github.kittinunf.fuel.core.deserializers.StringDeserializer10import com.github.kittinunf.fuel.core.response11import com.github.kittinunf.result.Result12import java.nio.charset.Charset13/**14 * Created by Ihor Kucherenko on 01.06.17.15 * https://github.com/KucherenkoIhor16 */17fun Request.liveDataResponse() = liveDataResponse(ByteArrayDeserializer())18fun Request.liveDataResponseString(charset: Charset = Charsets.UTF_8) = liveDataResponse(StringDeserializer(charset))19fun <T : Any> Request.liveDataResponseObject(deserializable: Deserializable<T>) = liveDataResponse(deserializable)20private fun <T : Any> Request.liveDataResponse(deserializable: Deserializable<T>): LiveData<Pair<Response, Result<T, FuelError>>> {21    val liveData = MutableLiveData<Pair<Response, Result<T, FuelError>>>()22    val handler: (Request, Response, Result<T, FuelError>) -> Unit = { _, response, result ->23        liveData.value = response to result24    }25    response(deserializable, handler)26    return liveData27}28fun Request.liveDataBytes() = liveDataResult(ByteArrayDeserializer())29fun Request.liveDataString(charset: Charset = Charsets.UTF_8) = liveDataResult(StringDeserializer(charset))30fun <T : Any> Request.liveDataObject(deserializable: Deserializable<T>) = liveDataResult(deserializable)31private fun <T : Any> Request.liveDataResult(deserializable: Deserializable<T>): LiveData<Result<T, FuelError>> {32    val liveData = MutableLiveData<Result<T, FuelError>>()33    val handler: (Request, Response, Result<T, FuelError>) -> Unit = { _, _, result ->34        liveData.value = result35    }36    response(deserializable, handler)37    return liveData38}...misc.kt
Source:misc.kt  
2import com.github.kittinunf.fuel.core.Deserializable3import com.github.kittinunf.fuel.core.Request4import com.github.kittinunf.fuel.core.Response5import com.github.kittinunf.fuel.core.ResponseOf6import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer7import com.github.kittinunf.fuel.coroutines.await8import com.github.kittinunf.fuel.coroutines.awaitObjectResponse9import com.github.kittinunf.fuel.coroutines.awaitResponse10import kotlinx.coroutines.*11import kotlinx.coroutines.channels.Channel12import kotlin.coroutines.CoroutineContext13/**14 * Run function on IO thread15 */16suspend fun <T>io(17    start: CoroutineStart = CoroutineStart.DEFAULT,18    block: suspend CoroutineScope.() -> T19): T = GlobalScope.async(Dispatchers.IO, start, block).await()20/**...RxFuel.kt
Source:RxFuel.kt  
1package com.github.kittinunf.fuel.rx2import com.github.kittinunf.fuel.core.*3import com.github.kittinunf.fuel.core.deserializers.ByteArrayDeserializer4import com.github.kittinunf.fuel.core.deserializers.StringDeserializer5import com.github.kittinunf.result.Result6import io.reactivex.Single7import java.nio.charset.Charset8fun Request.rx_response() = rx_response(ByteArrayDeserializer())9fun Request.rx_responseString(charset: Charset = Charsets.UTF_8) = rx_response(StringDeserializer(charset))10fun <T : Any> Request.rx_responseObject(deserializable: Deserializable<T>) = rx_response(deserializable)11private fun <T : Any> Request.rx_response(deserializable: Deserializable<T>): Single<Pair<Response, Result<T, FuelError>>> =12        Single.create { emitter ->13            val (_, response, result) = response(deserializable)14            emitter.onSuccess(response to result)15            emitter.setCancellable { this.cancel() }16        }17fun Request.rx_bytes() = rx_result(ByteArrayDeserializer())18fun Request.rx_string(charset: Charset = Charsets.UTF_8) = rx_result(StringDeserializer(charset))19fun <T : Any> Request.rx_object(deserializable: Deserializable<T>) = rx_result(deserializable)20private fun <T : Any> Request.rx_result(deserializable: Deserializable<T>): Single<Result<T, FuelError>> =21        Single.create { emitter ->22            val (_, _, result) = response(deserializable)23            emitter.onSuccess(result)24            emitter.setCancellable { this.cancel() }25        }...ByteArrayDeserializer.kt
Source:ByteArrayDeserializer.kt  
1package com.github.kittinunf.fuel.core.deserializers2import com.github.kittinunf.fuel.core.Deserializable3import com.github.kittinunf.fuel.core.Response4class ByteArrayDeserializer : Deserializable<ByteArray> {5    override fun deserialize(response: Response): ByteArray = response.data6}...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
