How to use Encoding class of com.github.kittinunf.fuel.core package

Best Fuel code snippet using com.github.kittinunf.fuel.core.Encoding

HttpClient.kt

Source:HttpClient.kt Github

copy

Full Screen

...104 { key, value -> addRequestProperty(key, value) }105 )106 // By default, the Android implementation of HttpURLConnection requests that servers use gzip compression107 // and it automatically decompresses the data for callers of URLConnection.getInputStream().108 // The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can109 // be disabled by setting the acceptable encodings in the request header:110 //111 // .header(Headers.ACCEPT_ENCODING, "identity")112 //113 // However, on the JVM, this behaviour might be different. Content-Encoding SHOULD NOT be used, in HTTP/1x114 // to act as Transfer Encoding. In HTTP/2, Transfer-Encoding is not part of the Connection field and should115 // not be injected here. HttpURLConnection is only HTTP/1x, whereas Java 9 introduces a new HttpClient for116 // HTTP/2.117 //118 // This adds the TE header for HTTP/1 connections, and automatically decodes it using decodeTransfer.119 // The TE (Accept Transfer Encoding) can only be one of these, should match decodeTransfer.120 setRequestProperty(121 Headers.ACCEPT_TRANSFER_ENCODING,122 Headers.collapse(HeaderName(Headers.ACCEPT_TRANSFER_ENCODING), SUPPORTED_DECODING)123 )124 hook.preConnect(connection, request)125 setDoOutput(connection, request.method)126 setBodyIfDoOutput(connection, request)127 }128 // Ensure that we are connected after this point. Note that getOutputStream above will129 // also connect and exchange HTTP messages.130 connection.connect()131 }132 @Throws(IOException::class, InterruptedException::class)133 private fun retrieveResponse(request: Request, connection: HttpURLConnection): Response {134 ensureRequestActive(request, connection)135 hook.postConnect(request)136 val headers = Headers.from(connection.headerFields)137 val transferEncoding = headers[Headers.TRANSFER_ENCODING].flatMap { it.split(',') }.map { it.trim() }138 val contentEncoding = headers[Headers.CONTENT_ENCODING].lastOrNull()139 var contentLength = headers[Headers.CONTENT_LENGTH].lastOrNull()?.toLong()140 val shouldDecode = (request.executionOptions.decodeContent ?: decodeContent) && contentEncoding != null && contentEncoding != "identity"141 if (shouldDecode) {142 // `decodeContent` decodes the response, so the final response has no more `Content-Encoding`143 headers.remove(Headers.CONTENT_ENCODING)144 // URLConnection.getContentLength() returns the number of bytes transmitted and cannot be used to predict145 // how many bytes can be read from URLConnection.getInputStream() for compressed streams. Therefore if the146 // stream will be decoded, the length becomes unknown147 //148 headers.remove(Headers.CONTENT_LENGTH)149 contentLength = null150 }151 // `decodeTransfer` decodes the response, so the final response has no more Transfer-Encoding152 headers.remove(Headers.TRANSFER_ENCODING)153 // [RFC 7230, 3.3.2](https://tools.ietf.org/html/rfc7230#section-3.3.2)154 //155 // When a message does not have a Transfer-Encoding header field, a156 // Content-Length header field can provide the anticipated size, as a157 // decimal number of octets, for a potential payload body.158 //159 // A sender MUST NOT send a Content-Length header field in any message160 // that contains a Transfer-Encoding header field.161 //162 // [RFC 7230, 3.3.3](https://tools.ietf.org/html/rfc7230#section-3.3.3)163 //164 // Any 2xx (Successful) response to a CONNECT request implies that165 // the connection will become a tunnel immediately after the empty166 // line that concludes the header fields. A client MUST ignore any167 // Content-Length or Transfer-Encoding header fields received in168 // such a message.169 //170 if (transferEncoding.any { encoding -> encoding.isNotBlank() && encoding != "identity" }) {171 headers.remove(Headers.CONTENT_LENGTH)172 contentLength = -1173 }174 val contentStream = dataStream(request, connection)?.decode(transferEncoding) ?: ByteArrayInputStream(ByteArray(0))175 val inputStream = if (shouldDecode && contentEncoding != null) contentStream.decode(contentEncoding) else contentStream176 val cancellationConnection = WeakReference<HttpURLConnection>(connection)177 val progressStream = ProgressInputStream(178 inputStream, onProgress = { readBytes ->179 request.executionOptions.responseProgress(readBytes, contentLength ?: readBytes)180 ensureRequestActive(request, cancellationConnection.get())181 }182 )183 // The input and output streams returned by connection are not buffered. In order to give consistent progress184 // reporting, by means of flushing, the input stream here is buffered.185 return Response(186 url = request.url,187 headers = headers,188 contentLength = contentLength ?: -1,189 statusCode = connection.responseCode,...

Full Screen

Full Screen

purge.kt

Source:purge.kt Github

copy

Full Screen

1import com.github.kittinunf.fuel.core.Headers2import com.github.kittinunf.fuel.httpDelete3import com.github.kittinunf.fuel.httpGet4import com.github.kittinunf.result.failure5import mu.KotlinLogging6import java.io.File7private val logger = KotlinLogging.logger {}8fun purge() {9 val completedTasks = getCompletedTasks()10 logger.debug { "Result: ${completedTasks.size} row(s)" }11 val tasksFile = File("tasks")12 if (!tasksFile.exists()) tasksFile.mkdir()13 if (tasksFile.isDirectory && tasksFile.canWrite())14 completedTasks.forEach { task ->15 logger.debug { " ${task.id}" }16 dumpAndRemove(task)17 }18}19fun dumpAndRemove(task: Task) {20 File("tasks/${task.id}.json").writeText(task.json.toString())21 removeTask(task.id)22}23fun removeTask(id: String) {24 val (_, response, result) = "$TASKS/$id"25 .httpDelete()26 .header(27 "Host" to "maxdone.micromiles.co",28 Headers.USER_AGENT to UA,29 Headers.ACCEPT to "application/json, text/javascript, */*; q=0.01",30 Headers.ACCEPT_LANGUAGE to "en-US,en;q=0.5",31 Headers.ACCEPT_ENCODING to "gzip, deflate, br",32 "X-Requested-With" to "XMLHttpRequest",33 "Origin" to "https://maxdone.micromiles.co",34 "DNT" to "1",35 "Connection" to "keep-alive",36 "Referer" to "https://maxdone.micromiles.co/personal",37 Headers.COOKIE to cookieStore.allCookies()38 )39 .response()40 result.fold(41 success = {42 logger.debug { " delete resulted in ${response.statusCode}" }43 },44 failure = {45 logger.error { it }46 throw it47 }48 )49}50private fun getCompletedTasks(): List<Task> {51 val (_, _, result) = TASKS_COMPLETED52 .httpGet(listOf("size" to PAGE_SIZE.toString(), "page" to "0", "format" to "json"))53 .header(54 Headers.ACCEPT to "application/json, text/javascript, */*; q=0.01",55 Headers.ACCEPT_ENCODING to "gzip, deflate, br",56 Headers.ACCEPT_LANGUAGE to "en-US,en;q=0.5",57 "Connection" to "keep-alive",58 Headers.COOKIE to cookieStore.allCookies(),59 "DNT" to "1",60 "Host" to "maxdone.micromiles.co",61 "Referer" to PERSONAL,62 Headers.USER_AGENT to UA,63 "X-Requested-With" to "XMLHttpRequest"64 )65 .responseObject(Task.CompletedListDeserializer())66 result.failure { throw it }67 return result.get()68}...

Full Screen

Full Screen

HttpAccessor.kt

Source:HttpAccessor.kt Github

copy

Full Screen

23import android.content.ContentValues.TAG4import android.nfc.Tag5import android.util.Log6import com.fasterxml.jackson.core.JsonEncoding7import com.fasterxml.jackson.databind.ObjectMapper8import com.fasterxml.jackson.module.kotlin.readValue9import com.fasterxml.jackson.module.kotlin.registerKotlinModule10import com.github.kittinunf.fuel.Fuel11import com.github.kittinunf.fuel.core.FuelManager12import com.github.kittinunf.fuel.core.Response13import com.github.kittinunf.fuel.httpGet14import com.github.kittinunf.fuel.json.responseJson15import com.github.kittinunf.result.Result16import kotlinx.coroutines.CoroutineScope17import org.json.JSONObject18import response.ResponseContentJSON19import url.Path20import java.lang.Exception ...

Full Screen

Full Screen

RedirectionInterceptor.kt

Source:RedirectionInterceptor.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core.interceptors2import com.github.kittinunf.fuel.core.Encoding3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.Headers5import com.github.kittinunf.fuel.core.Method6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.Response8import com.github.kittinunf.fuel.core.isStatusRedirection9import java.net.URI10import java.net.URL11import javax.net.ssl.HttpsURLConnection12private val redirectStatusWithGets = listOf(13 HttpsURLConnection.HTTP_MOVED_PERM,14 HttpsURLConnection.HTTP_MOVED_TEMP,15 HttpsURLConnection.HTTP_SEE_OTHER16)17fun redirectResponseInterceptor(manager: FuelManager) =18 { next: (Request, Response) -> Response ->19 inner@{ request: Request, response: Response ->20 if (!response.isStatusRedirection || request.executionOptions.allowRedirects == false) {21 return@inner next(request, response)22 }23 val redirectedUrl = response[Headers.LOCATION]24 .ifEmpty { response[Headers.CONTENT_LOCATION] }25 .lastOrNull()26 if (redirectedUrl.isNullOrEmpty()) {27 return@inner next(request, response)28 }29 val newUrl = if (URI(redirectedUrl.split('?').first()).isAbsolute) URL(redirectedUrl) else URL(request.url, redirectedUrl)30 val newMethod = when {31 response.statusCode in redirectStatusWithGets -> Method.GET32 else -> request.method33 }34 val encoding = Encoding(httpMethod = newMethod, urlString = newUrl.toString())35 val newRequest = manager.request(encoding)36 .header(Headers.from(request.headers))37 .also {38 // Check whether it is the same host or not39 if (newUrl.host != request.url.host)40 it.headers.remove(Headers.AUTHORIZATION)41 }42 .requestProgress(request.executionOptions.requestProgress)43 .responseProgress(request.executionOptions.responseProgress)44 .let {45 if (newMethod === request.method && !request.body.isEmpty() && !request.body.isConsumed())46 it.body(request.body)47 else48 it...

Full Screen

Full Screen

HttpClientTest.kt

Source:HttpClientTest.kt Github

copy

Full Screen

1package com.github.vitormbgoncalves.todolist.oauth.client2import com.github.kittinunf.fuel.core.Encoding3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.Method5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.RequestFactory7import com.github.kittinunf.fuel.test.MockHttpTestCase8import org.spekframework.spek2.Spek9import org.spekframework.spek2.style.specification.describe10/**11 * Http client request testing12 *13 * @author Vitor Goncalves14 * @since 07.05.2021, sex, 10:4715 */16class HttpClientTest : MockHttpTestCase() {17 class RequestTest : Spek({18 val manager: FuelManager by lazy { FuelManager() }19 class PathStringConvertibleImpl(url: String) : RequestFactory.PathStringConvertible {20 override val path = url21 }22 class RequestConvertibleImpl(val method: Method, private val url: String) : RequestFactory.RequestConvertible {23 override val request = createRequest()24 private fun createRequest(): Request {25 val encoder = Encoding(26 httpMethod = method,27 urlString = url,28 parameters = listOf("foo" to "bar")29 )30 return encoder.request31 }32 }33 describe("Http client request") {34 it("should be OK") {35 fun testResponseURLShouldSameWithRequestURL() {36 mock.chain(37 request = mock.request().withMethod(Method.GET.value).withPath("/request"),38 response = mock.reflect()39 )...

Full Screen

Full Screen

ContentEncodingTest.kt

Source:ContentEncodingTest.kt Github

copy

Full Screen

...10import org.junit.Test11import org.mockserver.model.Header12import java.io.ByteArrayOutputStream13import java.util.zip.GZIPOutputStream14class ContentEncodingTest : MockHttpTestCase() {15 @Test16 fun gzipContentEncodingTest() {17 val value = ByteArray(32).apply {18 for (i in 0..(this.size - 1)) {19 this[i] = ('A'..'z').random().toByte()20 }21 }22 val inner = ByteArrayOutputStream(value.size)23 val output = GZIPOutputStream(inner)24 output.write(value)25 output.finish()26 // It's written to here27 val gzipped = inner.toByteArray()28 mock.chain(29 request = mock.request()30 .withMethod(Method.POST.value)...

Full Screen

Full Screen

http.kt

Source:http.kt Github

copy

Full Screen

...15class FuelHttpService {16 fun textUrl(url: String, parameters: List<Pair<String, Any?>>? = null): Promise<String, Exception> {17 return Fuel.get(url, parameters).promise() then {18 val (request, response, bytes) = it19 String(bytes, Charset.forName(response.contentTypeEncoding))20 }21 }22 fun bitmapUrl(url: String): Promise<Bitmap, Exception> {23 return Fuel.get(url).promise() then {24 BitmapFactory.decodeStream(ByteArrayInputStream(it.third))25 }26 }27}28fun Request.promise(): Promise<Triple<Request, Response, ByteArray>, Exception> {29 val deferred = deferred<Triple<Request, Response, ByteArray>, Exception>()30 task { response() } success {31 val (request, response, result) = it32 when(result) {33 is Result.Success -> deferred.resolve(Triple(request, response, result.value))34 is Result.Failure -> deferred.reject(result.error)35 }36 } fail {37 deferred.reject(it)38 }39 return deferred.promise40}41val Response.contentTypeEncoding: String42 get() = contentTypeEncoding()43fun Response.contentTypeEncoding(default: String = "utf-8"): String {44 val contentType: String = httpResponseHeaders["Content-Type"]?.first() ?: return default45 return contentType.substringAfterLast("charset=", default).substringAfter(' ', default)46}...

Full Screen

Full Screen

FuelRouting.kt

Source:FuelRouting.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.util2import com.github.kittinunf.fuel.core.Encoding3import com.github.kittinunf.fuel.core.HeaderValues4import com.github.kittinunf.fuel.core.Method5import com.github.kittinunf.fuel.core.Parameters6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.RequestFactory8/**9 * Created by matteocrippa on 8/16/17.10 */11interface FuelRouting : RequestFactory.RequestConvertible {12 /**13 * Base path handler for the remote call.14 */15 val basePath: String16 /**17 * Method handler for the remote requests.18 */19 val method: Method20 /**21 * Path handler for the request.22 */23 val path: String24 /**25 * Parameters for the remote call.26 * It uses a pair with String, Any.27 */28 val params: Parameters?29 /**30 * Body to handle binary type of request (e.g. application/octet-stream )31 */32 val bytes: ByteArray?33 /**34 * Body to handle other type of request (e.g. application/json )35 */36 val body: String?37 /**38 * Headers for remote call.39 */40 val headers: Map<String, HeaderValues>?41 /**42 * @return a Request object.43 * Request call, it adheres to Fuel.RequestConvertible.44 */45 override val request: Request46 get() {47 // generate the encoder according provided parameters, headers, path, etc.48 val request = Encoding(49 baseUrlString = basePath,50 httpMethod = method,51 urlString = path,52 parameters = params53 ).request54 body?.let { request.body(it) } ?: bytes?.let { request.body(it) }55 // return the generated encoder with custom header injected56 return request.header(headers ?: emptyMap())57 }58}...

Full Screen

Full Screen

Encoding

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.core.Encoding2import com.github.kittinunf.fuel.core.Response3import com.github.kittinunf.result.Result4import com.github.kittinunf.fuel.core.FuelManager5import com.github.kittinunf.fuel.core.Method6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.RequestConvertible8import com.github.kittinunf.fuel.core.RequestFactory9import com.github.kittinunf.fuel.core.RequestProgressCallback10import com.github.kittinunf.fuel.core.RequestProgressCallback11import com.github.kittinunf.fuel.core.ResponseDeserializable12import com.github.kittinunf.fuel.core.ResponseResultOf13import com.github.kittinunf.fuel.core.ResponseResultOf14import com.github.kittinunf.fuel.core.ResponseResultOf15import com.github.kittinunf.fuel.core.ResponseResultOf

Full Screen

Full Screen

Encoding

Using AI Code Generation

copy

Full Screen

1 FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")2 FuelManager.instance.baseParams = listOf("param" to "value")3 .responseObject(DeserializableOf<HttpBinUserAgentModel>())4 println(result)5}6data class HttpBinUserAgentModel(val userAgent: String = "")7class DeserializableOf<T : Any>(val type: Class<T>) : ResponseDeserializable<T> {8 override fun deserialize(content: String): T? {9 return Gson().fromJson(content, type)10 }11}12@Suppress("UNCHECKED_CAST")13class DeserializableOf2<T : Any>(val type: Class<T>) : ResponseDeserializable<T> {14 override fun deserialize(content: String): T? {15 return Gson().fromJson(content, type) as T16 }17}18@Suppress("UNCHECKED_CAST")19class DeserializableOf3<T : Any>(val type: Class<T>) : ResponseDeserializable<T> {20 override fun deserialize(content: String): T? {21 return Gson().fromJson(content, type) as? T22 }23}24@Suppress("UNCHECKED_CAST")25class DeserializableOf4<T : Any>(val type: Class<T>) : ResponseDeserializable<T> {26 override fun deserialize(content: String): T? {27 return Gson().fromJson(content, type) as? T28 }29}30@Suppress("UNCHECKED_CAST")31class DeserializableOf5<T : Any>(val type: Class<T>) : ResponseDeserializable<T> {32 override fun deserialize(content: String): T? {33 return Gson().fromJson(content, type) as? T34 }35}36@Suppress("UNCHECKED_CAST")37class DeserializableOf6<T : Any>(val type: Class<T>) : ResponseDeserializable<T> {38 override fun deserialize(content: String): T? {39 return Gson().fromJson(content, type) as? T40 }41}42@Suppress("UNCHECKED_CAST")43class DeserializableOf7<T : Any>(val type: Class<T>) : ResponseDeserializable<T> {44 override fun deserialize(content: String): T? {

Full Screen

Full Screen

Encoding

Using AI Code Generation

copy

Full Screen

1println(String(response.data, Charset.forName("UTF-8")))2println(String(response.data, Charset.forName("UTF-8")))3println(String(response.data, Charset.forName("UTF-8")))4println(String(response.data, Charset.forName("UTF-8")))5println(String(response.data, Charset.forName("UTF-8")))6println(String(response.data, Charset.forName("UTF-8")))7println(String(response.data, Charset.forName("UTF-8")))8println(String(response.data, Charset.forName("UTF-8")))9println(String(response.data, Charset.forName("UTF-8")))10println(String(response.data, Charset.forName("UTF-8")))11println(String(response.data, Charset.forName("UTF-8")))

Full Screen

Full Screen

Encoding

Using AI Code Generation

copy

Full Screen

1 fun encodeBase64(data: ByteArray): String {2 return String(Base64.getEncoder().encode(data))3 }4 fun decodeBase64(data: String): ByteArray {5 return Base64.getDecoder().decode(data)6 }

Full Screen

Full Screen

Encoding

Using AI Code Generation

copy

Full Screen

1val encoding = Encoding(response)2println(encoding)3val encoding = Encoding(response)4println(encoding)5val encoding = Encoding(response)6println(encoding)7val encoding = Encoding(response)8println(encoding)9val encoding = Encoding(response)10println(encoding)11val encoding = Encoding(response)12println(encoding)13val encoding = Encoding(response)14println(encoding)15val encoding = Encoding(response)16println(encoding)17val encoding = Encoding(response)18println(encoding)19val encoding = Encoding(response)20println(encoding)21val encoding = Encoding(response)22println(encoding)23val encoding = Encoding(response)24println(encoding)25val encoding = Encoding(response)26println(encoding)27val encoding = Encoding(response)28println(encoding

Full Screen

Full Screen

Encoding

Using AI Code Generation

copy

Full Screen

1val encodedURL = URL.encodeURL(url)2val encodedURL = URLEncoder.encode(url, "UTF-8")3fun String.encodeURL(): String = URLEncoder.encode(this, "UTF-8")4public static String encodeURL(String url) throws UnsupportedEncodingException {5 return URLEncoder.encode(url, "UTF-8");6}7fun String.encodeURL(): String = URLEncoder.encode(this, "UTF-8")8public static String encodeURL(String url) throws UnsupportedEncodingException {9 return URLEncoder.encode(url, "UTF-8");10}11fun String.encodeURL(): String = URLEncoder.encode(this, "UTF-8")12public static String encodeURL(String url) throws UnsupportedEncodingException {13 return URLEncoder.encode(url, "UTF-8");14}15fun String.encodeURL(): String = URLEncoder.encode(this, "UTF-8")16public static String encodeURL(String url) throws UnsupportedEncodingException {17 return URLEncoder.encode(url, "UTF-8");18}19fun String.encodeURL(): String = URLEncoder.encode(this, "UTF-8")20public static String encodeURL(String url) throws UnsupportedEncodingException {21 return URLEncoder.encode(url, "UTF-8");22}23fun String.encodeURL(): String = URLEncoder.encode(this, "UTF-8")24public static String encodeURL(String url) throws UnsupportedEncodingException {25 return URLEncoder.encode(url, "UTF-8");26}

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.

Most used methods in Encoding

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful