How to use header method of com.github.kittinunf.fuel.core.requests.DefaultRequest class

Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.DefaultRequest.header

DefaultRequest.kt

Source:DefaultRequest.kt Github

copy

Full Screen

...31import 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>) =...

Full Screen

Full Screen

ParameterEncoderTest.kt

Source:ParameterEncoderTest.kt Github

copy

Full Screen

...107 val testRequest = DefaultRequest(108 method,109 URL("https://test.fuel.com"),110 parameters = listOf("foo" to "bar")111 ).header(Headers.CONTENT_TYPE, "multipart/form-data")112 .upload()113 .add { BlobDataPart(ByteArrayInputStream("12345678".toByteArray()), name = "test", contentLength = 8L) }114 var executed = false115 ParameterEncoder { request ->116 assertThat(request.url.toExternalForm(), not(containsString("?")))117 assertThat(request.url.query, not(containsString("foo=bar")))118 val contentType = request[Headers.CONTENT_TYPE].lastOrNull()?.split(';')?.first()119 assertThat(contentType, equalTo("multipart/form-data"))120 val body = String(request.body.toByteArray())121 assertThat(body, containsString("foo"))122 assertThat(body, containsString("bar"))123 assertThat(body, containsString("test"))124 assertThat(body, containsString("12345678"))125 assertThat("Expected parameters not to be cleared", request.parameters.isEmpty(), equalTo(false))...

Full Screen

Full Screen

RequestHeadersTest.kt

Source:RequestHeadersTest.kt Github

copy

Full Screen

...10class RequestHeadersTest {11 @Test12 fun requestHeadersFromReadmeIntegrity() {13 val request = DefaultRequest(method = Method.POST, url = URL("https://test.fuel.com/my-post-path"))14 .header(Headers.ACCEPT, "text/html, */*; q=0.1")15 .header(Headers.CONTENT_TYPE, "image/png")16 .header(Headers.COOKIE to "basic=very")17 .appendHeader(Headers.COOKIE to "value_1=foo", Headers.COOKIE to "value_2=bar", Headers.ACCEPT to "application/json")18 .appendHeader("MyFoo" to "bar", "MyFoo" to "baz")19 val recordedSets = mutableMapOf<String, String>()20 request.headers.transformIterate(21 { key: String, value: String -> recordedSets.put(key, value) },22 { k, v -> fail("Expected only header `set` and `add` with $k and $v") }23 )24 assertThat(recordedSets[Headers.ACCEPT], equalTo("text/html, */*; q=0.1, application/json"))25 assertThat(recordedSets[Headers.CONTENT_TYPE], equalTo("image/png"))26 assertThat(recordedSets[Headers.COOKIE], equalTo("basic=very; value_1=foo; value_2=bar"))27 assertThat(recordedSets["MyFoo"], equalTo("bar, baz"))28 }29 @Test30 fun requestHasHeaderGetter() {31 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))32 .header(Headers.CONTENT_TYPE, "text/html")33 val values = request[Headers.CONTENT_TYPE]34 assertThat(values, equalTo(request.header(Headers.CONTENT_TYPE)))35 assertThat(values.lastOrNull(), equalTo("text/html"))36 }37 @Test38 fun requestHasHeaderSetter() {39 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))40 request[Headers.CONTENT_TYPE] = "text/html"41 val values = request.header(Headers.CONTENT_TYPE)42 assertThat(values.lastOrNull(), equalTo("text/html"))43 assertThat(values.size, equalTo(1))44 }45 @Test46 fun setHeaderSetterSingleReplacesOldValue() {47 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))48 .header(Headers.CONTENT_TYPE, "text/html")49 request[Headers.CONTENT_TYPE] = "text/plain"50 val values = request.header(Headers.CONTENT_TYPE)51 assertThat(values.lastOrNull(), equalTo("text/plain"))52 assertThat(values.size, equalTo(1))53 }54 @Test55 fun setHeaderFunctionSingleReplacesOldValue() {56 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))57 .header(Headers.CONTENT_TYPE, "text/html")58 request.header(Headers.CONTENT_TYPE, "application/json")59 val values = request.header(Headers.CONTENT_TYPE)60 assertThat(values.lastOrNull(), equalTo("application/json"))61 assertThat(values.size, equalTo(1))62 }63 @Test64 fun setHeaderSetterMultipleReplacesOldValue() {65 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))66 .header(Headers.ACCEPT, "text/html")67 request[Headers.ACCEPT] = listOf("text/plain", "*/*; q=0.2")68 val values = request.header(Headers.ACCEPT)69 assertThat(values.firstOrNull(), equalTo("text/plain"))70 assertThat(values.lastOrNull(), equalTo("*/*; q=0.2"))71 assertThat(values.size, equalTo(2))72 }73 @Test74 fun setHeaderFunctionMultipleReplacesOldValue() {75 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))76 .header(Headers.ACCEPT, "text/html")77 request.header(Headers.ACCEPT, listOf("text/plain", "*/*; q=0.2"))78 val values = request.header(Headers.ACCEPT)79 assertThat(values.firstOrNull(), equalTo("text/plain"))80 assertThat(values.lastOrNull(), equalTo("*/*; q=0.2"))81 assertThat(values.size, equalTo(2))82 }83 @Test84 fun setHeaderFunctionMapReplacesOldValue() {85 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))86 .header(Headers.ACCEPT, "text/html")87 request.header(mapOf(Headers.ACCEPT to listOf("text/plain", "*/*; q=0.2")))88 val values = request.header(Headers.ACCEPT)89 assertThat(values.firstOrNull(), equalTo("text/plain"))90 assertThat(values.lastOrNull(), equalTo("*/*; q=0.2"))91 assertThat(values.size, equalTo(2))92 }93 @Test94 fun setHeaderFunctionPairsReplacesOldValue() {95 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))96 .header(Headers.ACCEPT, "text/html")97 request.header(Headers.ACCEPT to listOf("text/plain", "*/*; q=0.2"))98 val values = request.header(Headers.ACCEPT)99 assertThat(values.firstOrNull(), equalTo("text/plain"))100 assertThat(values.lastOrNull(), equalTo("*/*; q=0.2"))101 assertThat(values.size, equalTo(2))102 }103 @Test104 fun setHeaderFunctionVarArgsReplacesOldValue() {105 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))106 .header(Headers.ACCEPT, "text/html")107 request.header(Headers.ACCEPT, "text/plain", "*/*; q=0.2")108 val values = request.header(Headers.ACCEPT)109 assertThat(values.firstOrNull(), equalTo("text/plain"))110 assertThat(values.lastOrNull(), equalTo("*/*; q=0.2"))111 assertThat(values.size, equalTo(2))112 }113 @Test114 fun setHeaderWithPairsPreservesDuplicateKeys() {115 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))116 .header(Headers.ACCEPT_ENCODING, "identity")117 request.header(Headers.ACCEPT_ENCODING to "br", Headers.ACCEPT_ENCODING to "gzip")118 val values = request.header(Headers.ACCEPT_ENCODING)119 assertThat(values.firstOrNull(), equalTo("br"))120 assertThat(values.lastOrNull(), equalTo("gzip"))121 assertThat(values.size, equalTo(2))122 }123 @Test124 fun setHeaderWithMapTakesLastKey() {125 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))126 .header(Headers.ACCEPT_ENCODING, "identity")127 request.header(mapOf(Headers.ACCEPT_ENCODING to "br", Headers.ACCEPT_ENCODING to "gzip"))128 val values = request.header(Headers.ACCEPT_ENCODING)129 assertThat(values.firstOrNull(), equalTo("gzip"))130 assertThat(values.size, equalTo(1))131 }132 @Test133 fun appendHeader() {134 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))135 .header(Headers.ACCEPT_LANGUAGE, "en-US", "nl-NL; q=0.9")136 request.appendHeader(Headers.ACCEPT_LANGUAGE, "fr-FR; q=0.8")137 val values = request.header(Headers.ACCEPT_LANGUAGE)138 assertThat(values.firstOrNull(), equalTo("en-US"))139 assertThat(values.lastOrNull(), equalTo("fr-FR; q=0.8"))140 assertThat(values.size, equalTo(3))141 }142 @Test143 fun appendHeaderWithVarArgs() {144 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))145 .header(Headers.ACCEPT_LANGUAGE, "en-US")146 request.appendHeader(Headers.ACCEPT_LANGUAGE, "nl-NL; q=0.9", "fr-FR; q=0.8")147 val values = request.header(Headers.ACCEPT_LANGUAGE)148 assertThat(values.firstOrNull(), equalTo("en-US"))149 assertThat(values.lastOrNull(), equalTo("fr-FR; q=0.8"))150 assertThat(values.size, equalTo(3))151 }152 @Test153 fun appendHeaderWithPairs() {154 val request = DefaultRequest(method = Method.GET, url = URL("https://test.fuel.com/"))155 .header(Headers.ACCEPT_LANGUAGE, "en-US")156 request.appendHeader(Headers.ACCEPT_LANGUAGE to "nl-NL; q=0.9", Headers.ACCEPT_LANGUAGE to "fr-FR; q=0.8")157 val values = request.header(Headers.ACCEPT_LANGUAGE)158 assertThat(values.firstOrNull(), equalTo("en-US"))159 assertThat(values.lastOrNull(), equalTo("fr-FR; q=0.8"))160 assertThat(values.size, equalTo(3))161 }162}...

Full Screen

Full Screen

FuelExtensionsTest.kt

Source:FuelExtensionsTest.kt Github

copy

Full Screen

...26import kotlin.test.assertTrue27class FuelExtensionsTest {28 private val basicRetryResponse = createRetryResponse("0")29 @Test30 fun `token adds Token Authorization header to request`() {31 val request = DefaultRequest(Method.GET, URL("https://example.com/authentication"))32 .authentication().token("token")33 assertThat(request[Headers.AUTHORIZATION].lastOrNull(), equalTo("Token token"))34 }35 @Test36 fun `responseStringWithRetries returns final response when succeeding within retry count`() {37 val client = mock<Client>()38 `when`(client.executeRequest(any()))39 .thenReturn(basicRetryResponse)40 .thenReturn(41 Response(42 statusCode = 200,43 url = URL("https://example.com"),44 body = DefaultBody.from({ ByteArrayInputStream("final".toByteArray()) }, null)45 )46 )47 FuelManager.instance.client = client48 val (_, response, result) = Fuel.get("https://example.com")49 .responseStringWithRetries(1, 1L)50 assertEquals(200, response.statusCode)51 assertEquals("final", result.get())52 }53 @Test54 fun `responseStringWithRetries returns the last response when a non-throttle response is not received within retry count`() {55 val client = mock<Client>()56 `when`(client.executeRequest(any()))57 .thenReturn(basicRetryResponse)58 .thenReturn(basicRetryResponse)59 .thenReturn(basicRetryResponse) // One more than retry count60 .thenReturn(Response(statusCode = 200, url = URL("https://example.com")))61 FuelManager.instance.client = client62 val (_, response, result) = Fuel.get("https://example.com")63 .responseStringWithRetries(2, 1L) // Would have to be 3 to succeed64 assertEquals(429, response.statusCode) // Status code of last response65 assertTrue(result is Result.Failure)66 }67 @Test68 fun `responseStringWithRetries throws when an invalid Retry-After header is received`() {69 val client = mock<Client>()70 `when`(client.executeRequest(any())).thenReturn(createRetryResponse("INVALID VALUE"))71 FuelManager.instance.client = client72 assertThrows<NumberFormatException> {73 Fuel.get("https://example.com").responseStringWithRetries(1, 1L) // Would have to be 2 to succeed74 }75 }76 @Test77 fun `responseStringWithRetries throws when no Retry-After header is received in HTTP 429 response`() {78 val client = mock<Client>()79 `when`(client.executeRequest(any())).thenReturn(createRetryResponse("", Headers())) // No Retry-After header80 FuelManager.instance.client = client81 assertThrows<IllegalStateException> {82 Fuel.get("https://example.com").responseStringWithRetries(1)83 }84 }85 @Test86 fun `responseStringWithRetries returns non-throttled error by default`() {87 val client = mock<Client>()88 `when`(client.executeRequest(any())).thenReturn(89 Response(90 statusCode = 400,91 url = URL("https://example.com"),92 body = DefaultBody.from({ ByteArrayInputStream("unhandled error".toByteArray()) }, null)93 )94 )95 FuelManager.instance.client = client96 val (_, response, _) = Fuel.get("https://example.com").responseStringWithRetries(1)97 assertEquals(400, response.statusCode)98 assertEquals("unhandled error", response.body().asString("text/html"))99 }100 @Test101 fun `responseStringWithRetries returns fallback error handler's response when faced with a non-throttled error response`() {102 val client = mock<Client>()103 `when`(client.executeRequest(any())).thenReturn(104 Response(105 statusCode = 400,106 url = URL("https://example.com"),107 body = DefaultBody.from({ ByteArrayInputStream("unhandled error".toByteArray()) }, null)108 )109 )110 FuelManager.instance.client = client111 val (_, response, _) = Fuel.get("https://example.com").responseStringWithRetries(1) { r, _ ->112 ResponseResultOf(113 r.first,114 Response(115 statusCode = 400,116 url = URL("https://example.com"),117 body = DefaultBody.from({ ByteArrayInputStream("handled error".toByteArray()) }, null)118 ),119 r.third120 )121 }122 assertEquals(400, response.statusCode)123 assertEquals("handled error", response.body().asString("text/html"))124 }125 private fun createRetryResponse(126 retryAfter: String,127 headers: Headers = Headers.from(Headers.RETRY_AFTER to listOf(retryAfter))128 ) = Response(129 statusCode = 429,130 responseMessage = "RETRY",131 url = URL("https://example.com"),132 headers = headers133 )134}...

Full Screen

Full Screen

header

Using AI Code Generation

copy

Full Screen

1fun main(args: Array<String>) {2 .httpGet()3 .header(Pair("Content-Type", "application/json"))4 .header(Pair("Accept", "application/json"))5 .responseString()6 println("Request: $request")7 println("Response: $response")8 println("Result: $result")9}10fun main(args: Array<String>) {11 .httpGet()12 .header(mapOf("Content-Type" to "application/json",13 .responseString()14 println("Request: $request")15 println("Response: $response")16 println("Result: $result")17}18fun main(args: Array<String>) {19 .httpGet()20 .header("Content-Type" to "application/json",21 .responseString()22 println("Request: $request")23 println("Response: $response")24 println("Result: $result")25}26fun main(args: Array<String>) {27 .httpGet()28 .header("Content-Type" to "application/json",29 .responseString()30 println("Request: $request")31 println("Response: $response")32 println("Result: $result")33}34fun main(args: Array<String>) {35 .httpGet()36 .header("Content-Type" to "application/json",37 .responseString()38 println("Request: $request")39 println("Response: $

Full Screen

Full Screen

header

Using AI Code Generation

copy

Full Screen

1request.header("Content-Type" to "application/json")2request.header("Accept" to "application/json")3request.header("Content-Type" to "application/json")4request.header("Accept" to "application/json")5.header("Content-Type" to "application/json")6.header("Accept" to "application/json")7.header("Content-Type" to "application/json")8.header("Accept" to "application/json")9.header("Content-Type" to "application/json")10.header("Accept" to "application/json")11.header("Content-Type" to "application/json")12.header("Accept" to "application/json")

Full Screen

Full Screen

header

Using AI Code Generation

copy

Full Screen

1val header = mapOf("Content-Type" to "application/json")2val request = Fuel.get(url)3request.header(header)4request.response { _, _, result ->5result.fold({ d ->6println(d)7}, { err ->8println(err)9})10}11val request = Fuel.get(url)12request.header(Pair("Content-Type", "application/json"))13request.response { _, _, result ->14result.fold({ d ->15println(d)16}, { err ->17println(err)18})19}20val header = mapOf("Content-Type" to "application/json")21val request = Fuel.get(url, header)22request.response { _, _, result ->23result.fold({ d ->24println(d)25}, { err ->26println(err)27})28}29val request = Fuel.get(url, listOf("Content-Type" to "application/json"))30request.response { _, _, result ->31result.fold({ d ->32println(d)33}, { err ->34println(err)35})36}37val request = Fuel.get(url, "Content-Type" to "application/json")38request.response { _, _, result ->39result.fold({ d ->40println(d)41}, { err ->42println(err)43})44}45val request = Fuel.get(url, listOf("Content-Type" to "application/json"))46request.response { _, _, result ->47result.fold({ d ->48println(d)49}, { err ->50println(err)51})52}53val request = Fuel.get(url, "Content-Type

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