How to use ForceMethod class of com.github.kittinunf.fuel.toolbox.extensions package

Best Fuel code snippet using com.github.kittinunf.fuel.toolbox.extensions.ForceMethod

HttpClient.kt

Source:HttpClient.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.toolbox2import com.github.kittinunf.fuel.core.Client3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.FuelManager5import com.github.kittinunf.fuel.core.HeaderName6import com.github.kittinunf.fuel.core.Headers7import com.github.kittinunf.fuel.core.Method8import com.github.kittinunf.fuel.core.Request9import com.github.kittinunf.fuel.core.Response10import com.github.kittinunf.fuel.core.requests.DefaultBody11import com.github.kittinunf.fuel.core.requests.isCancelled12import com.github.kittinunf.fuel.toolbox.extensions.forceMethod13import com.github.kittinunf.fuel.util.ProgressInputStream14import com.github.kittinunf.fuel.util.ProgressOutputStream15import com.github.kittinunf.fuel.util.decode16import java.io.ByteArrayInputStream17import java.io.IOException18import java.io.InputStream19import java.lang.ref.WeakReference20import java.net.HttpURLConnection21import java.net.Proxy22import javax.net.ssl.HttpsURLConnection23import kotlin.coroutines.resume24import kotlin.coroutines.resumeWithException25import kotlin.coroutines.suspendCoroutine26import kotlin.math.max27class HttpClient(28 private val proxy: Proxy? = null,29 var useHttpCache: Boolean = true,30 var decodeContent: Boolean = true,31 var hook: Client.Hook32) : Client {33 override fun executeRequest(request: Request): Response {34 return try {35 doRequest(request)36 } catch (ioe: IOException) {37 hook.httpExchangeFailed(request, ioe)38 throw FuelError.wrap(ioe, Response(request.url))39 } catch (interrupted: InterruptedException) {40 throw FuelError.wrap(interrupted, Response(request.url))41 } finally {42 // As per Android documentation, a connection that is not explicitly disconnected43 // will be pooled and reused! So, don't close it as we need inputStream later!44 // connection.disconnect()45 }46 }47 @Throws(InterruptedException::class)48 private fun ensureRequestActive(request: Request, connection: HttpURLConnection?) {49 val cancelled = request.isCancelled50 if (!cancelled && !Thread.currentThread().isInterrupted) {51 return52 }53 // Flush all the pipes. This is necessary because we don't want the other end to wait for a timeout or hang.54 // This interrupts the connection correctly and makes the connection available later. This does break any55 // keep-alive on this particular connection56 connection?.disconnect()57 throw InterruptedException("[HttpClient] could not ensure Request was active: cancelled=$cancelled")58 }59 override suspend fun awaitRequest(request: Request): Response = suspendCoroutine { continuation ->60 try {61 continuation.resume(doRequest(request))62 } catch (ioe: IOException) {63 hook.httpExchangeFailed(request, ioe)64 continuation.resumeWithException(FuelError.wrap(ioe, Response(request.url)))65 } catch (interrupted: InterruptedException) {66 continuation.resumeWithException(FuelError.wrap(interrupted, Response(request.url)))67 }68 }69 @Throws(IOException::class, InterruptedException::class)70 private fun doRequest(request: Request): Response {71 val connection = establishConnection(request)72 sendRequest(request, connection)73 return retrieveResponse(request, connection)74 }75 @Throws(IOException::class, InterruptedException::class)76 private fun sendRequest(request: Request, connection: HttpURLConnection) {77 ensureRequestActive(request, connection)78 connection.apply {79 connectTimeout = max(request.executionOptions.timeoutInMillisecond, 0)80 readTimeout = max(request.executionOptions.timeoutReadInMillisecond, 0)81 if (this is HttpsURLConnection) {82 sslSocketFactory = request.executionOptions.socketFactory83 hostnameVerifier = request.executionOptions.hostnameVerifier84 }85 if (request.executionOptions.forceMethods) {86 forceMethod(request.method)87 // If setting method via reflection failed, invoke "coerceMethod"88 // and set "X-HTTP-Method-Override" header89 if (this.requestMethod !== request.method.value) {90 this.requestMethod = coerceMethod(request.method).value91 this.setRequestProperty("X-HTTP-Method-Override", request.method.value)92 }93 } else {94 requestMethod = coerceMethod(request.method).value95 if (request.method.value == "PATCH") {96 setRequestProperty("X-HTTP-Method-Override", request.method.value)97 }98 }99 doInput = true100 useCaches = request.executionOptions.useHttpCache ?: useHttpCache101 instanceFollowRedirects = false102 request.headers.transformIterate(103 { key, values -> setRequestProperty(key, values) },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,190 responseMessage = connection.responseMessage.orEmpty(),191 body = DefaultBody.from(192 { progressStream.buffered(FuelManager.progressBufferSize) },193 { contentLength ?: -1 }194 )195 )196 }197 private fun dataStream(request: Request, connection: HttpURLConnection): InputStream? = try {198 hook.interpretResponseStream(request, connection.inputStream)?.buffered()199 } catch (_: IOException) {200 hook.interpretResponseStream(request, connection.errorStream)?.buffered()201 }202 private fun establishConnection(request: Request): HttpURLConnection {203 val url = request.url204 val connection = proxy?.let { url.openConnection(it) } ?: url.openConnection()205 return connection as HttpURLConnection206 }207 private fun setBodyIfDoOutput(connection: HttpURLConnection, request: Request) {208 val body = request.body209 if (!connection.doOutput) {210 return211 }212 if (body.isEmpty()) {213 connection.setFixedLengthStreamingMode(0L)214 return215 }216 val contentLength = body.length217 if (contentLength != null && contentLength != -1L) {218 // The content has a known length, so no need to chunk219 connection.setFixedLengthStreamingMode(contentLength.toLong())220 } else {221 // The content doesn't have a known length, so turn it into chunked222 connection.setChunkedStreamingMode(4096)223 }224 val noProgressHandler = request.executionOptions.requestProgress.isNotSet()225 val outputStream = if (noProgressHandler) {226 // No need to report progress, let's just send the payload without buffering227 connection.outputStream228 } else {229 // The input and output streams returned by connection are not buffered. In order to give consistent progress230 // reporting, by means of flushing, the output stream here is buffered.231 val totalBytes = if ((contentLength ?: -1L).toLong() > 0) { contentLength!!.toLong() } else { null }232 ProgressOutputStream(233 connection.outputStream,234 onProgress = { writtenBytes ->235 request.executionOptions.requestProgress(writtenBytes, totalBytes ?: writtenBytes)236 ensureRequestActive(request, connection)237 }238 ).buffered(FuelManager.progressBufferSize)239 }240 body.writeTo(outputStream)241 connection.outputStream.flush()242 }243 private fun setDoOutput(connection: HttpURLConnection, method: Method) = when (method) {244 Method.GET, Method.HEAD, Method.OPTIONS, Method.TRACE -> connection.doOutput = false245 Method.DELETE, Method.POST, Method.PUT, Method.PATCH -> connection.doOutput = true246 }247 companion object {248 private val SUPPORTED_DECODING = listOf("gzip", "deflate; q=0.5")249 private fun coerceMethod(method: Method) = if (method == Method.PATCH) Method.POST else method250 }251}...

Full Screen

Full Screen

ForceMethodTest.kt

Source:ForceMethodTest.kt Github

copy

Full Screen

...5import org.junit.Assert.assertThat6import org.junit.Test7import java.net.HttpURLConnection8import java.net.URL9class ForceMethodTest : MockHttpTestCase() {10 @Test11 fun forceHttpPatchMethod() {12 val connection = URL(this.mock.path("force-patch-test")).openConnection()13 assert(connection is HttpURLConnection)14 val httpUrlConnection = connection as HttpURLConnection15 httpUrlConnection.forceMethod(Method.PATCH)16 assertThat(httpUrlConnection.requestMethod, equalTo(Method.PATCH.value))17 }18 @Test19 fun forceHttpPostMethod() {20 val connection = URL(this.mock.path("force-post-test")).openConnection()21 assert(connection is HttpURLConnection)22 val httpUrlConnection = connection as HttpURLConnection23 httpUrlConnection.forceMethod(Method.POST)...

Full Screen

Full Screen

ForceMethod.kt

Source:ForceMethod.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.toolbox.extensions2import com.github.kittinunf.fuel.core.Method3import java.net.HttpURLConnection4/**5 * Uses public setter "setRequestMethod" if method is support by HttpURLConnection6 * When method is PATCH, use reflection to set private field "method" on the HttpURLConnection instance7 * If reflection method fails, use "coerceMethod" and set appropriate "X-HTTP-Method-Override" header8 */9fun HttpURLConnection.forceMethod(method: Method) {10 when (method) {11 Method.PATCH -> {12 try {13 // If instance has private field "delegate" (HttpURLConnection), make the field accessible14 // and invoke "forceMethod" on that instance of HttpURLConnection15 (this.javaClass.getDeclaredField("delegate").apply {16 this.isAccessible = true17 }.get(this) as HttpURLConnection?)?.forceMethod(method)18 } catch (ex: NoSuchFieldException) {19 // ignore20 }21 this.forceMethod(this.javaClass, method)22 }23 else -> this.requestMethod = method.value24 }25}26private fun HttpURLConnection.forceMethod(clazz: Class<in HttpURLConnection>, method: Method) {27 try {28 clazz.getDeclaredField("method").apply {29 this.isAccessible = true30 }.set(this, method.value)31 } catch (ex: NoSuchFieldException) {32 if (HttpURLConnection::class.java.isAssignableFrom(clazz.superclass)) {33 this.forceMethod(clazz.superclass, method)34 }35 }36}...

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 println(request)2 println(response)3 println(result)4 println(request)5 println(response)6 println(result)7 println(request)8 println(response)9 println(result)10 println(request)11 println(response)12 println(result)13 println(request)14 println(response)15 println(result)16 println(request)17 println(response)18 println(result)19 println(request)20 println(response)21 println(result)22 println(request)23 println(response)24 println(result)

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1.method(Method.GET)2.forceMethod()3.responseString()4.method(Method.GET)5.forceMethod()6.responseString()7.method(Method.GET)8.forceMethod()9.responseString()10.method(Method.GET)11.forceMethod()12.responseString()13.method(Method.GET)14.forceMethod()15.responseString()16.method(Method.GET)17.forceMethod()18.responseString()19.method(Method.GET)20.forceMethod()21.responseString()22.method(Method.GET)23.forceMethod()24.responseString()25.method(Method.GET)26.forceMethod()27.responseString()28.method(Method.GET)29.forceMethod()30.responseString()

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1val forceMethod = ForceMethod()2 .forceMethod(forceMethod)3 .responseString()4val forceMethod = ForceMethod()5 .forceMethod(forceMethod)6 .responseString()

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 .body("Hello World")2 .forceMethod("PATCH")3 .responseString()4 println(request)5 println(response)6 println(result)7 .body("Hello World")8 .forceMethod("PUT")9 .responseString()10 println(request)11 println(response)12 println(result)13 at com.github.kittinunf.fuel.toolbox.HttpClient.executeRequest(HttpClient.kt:130)14 at com.github.kittinunf.fuel.core.requests.DefaultRequest.call(DefaultRequest.kt:21)15 at com.github.kittinunf.fuel.core.requests.DefaultRequest.call(DefaultRequest.kt:9)16 at com.github.kittinunf.fuel.core.FuelManager.callRequest(FuelManager.kt:55)17 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:65)18 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:70)19 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:70)20 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:70)21 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:70)22 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:70)23 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:70)24 at com.github.kittinunf.fuel.core.FuelManager.executeRequest(FuelManager.kt:70)25 at com.github.kittinunf.fuel.FuelKt$executeRequest$1.invoke(Fuel.kt:50)

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1val json = Gson().toJson(ForceMethod.GET)2FuelManager.instance.baseHeaders = mapOf("X-HTTP-Method-Override" to json)3FuelManager.instance.baseParams = listOf("foo" to "bar")4Fuel.get("/get").responseString { _, _, result ->5println(result)6}7val json = Gson().toJson(ForceMethod.GET)8FuelManager.instance.baseHeaders = mapOf("X-HTTP-Method-Override" to json)9FuelManager.instance.baseParams = listOf("foo" to "bar")10Fuel.get("/get").responseString { _, _, result ->11println(result)12}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 println(result)2}3 println(result)4}5 println(result)6}7 println(result)8}9 println(result)10}11 println(result)12}13 println(result)14}15 println(result)16}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1println(request)2println(response)3println(result)4}5println(request)6println(response)7println(result)8}9println(request)10println(response)11println(result)12}13println(request)14println(response)15println(result)16}17println(request)18println(response)19println(result)20}21println(request)22println(response)23println(result)24}25println(request)26println(response)27println(result)28}29println(request)30println(response)31println(result)32}33println(request)34println(response)35println(result)36}37println(request)38println(response)39println(result)40}41println(request)42println(response)43println(result)44}45println(request)46println(response)47println(result)48}49println(request)50println(response)51println(result)52}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 println(result.get())2}3 println(result.get())4}5 println(result.get())6}7 println(result.get())8}9 println(result.get())10}11println(request)12println(response)13println(result)14}15println(request)16println(response)17println(result)18}19println(request)20println(response)21println(result)22}23println(request)24println(response)25println(result)26}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 println(result.get())2}3 println(result.get())4}5 println(result.get())6}7 println(result.get())8}9 println(result.get())10}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1val json = Gson().toJson(ForceMethod.GET)2FuelManager.instance.baseHeaders = mapOf("X-HTTP-Method-Override" to json)3FuelManager.instance.baseParams = listOf("foo" to "bar")4Fuel.get("/get").responseString { _, _, result ->5println(result)6}7val json = Gson().toJson(ForceMethod.GET)8FuelManager.instance.baseHeaders = mapOf("X-HTTP-Method-Override" to json)9FuelManager.instance.baseParams = listOf("foo" to "bar")10Fuel.get("/get").responseString { _, _, result ->11println(result)12}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 println(result)2}3 println(result)4}5 println(result)6}7 println(result)8}9 println(result)10}11 println(result)12}13 println(result)14}15 println(result)16}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1println(request)2println(response)3println(result)4}5println(request)6println(response)7println(result)8}9println(request)10println(response)11println(result)12}13println(request)14println(response)15println(result)16}17println(request)18println(response)19println(result)20}21println(request)22println(response)23println(result)24}25println(request)26println(response)27println(result)28}29println(request)30println(response)31println(result)32}33println(request)34println(response)35println(result)36}37println(request)38println(response)39println(result)40}41println(request)42println(response)43println(result)44}45println(request)46println(response)47println(result)48}49println(request)50println(response)51println(result)52}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 println(result.get())2}3 println(result.get())4}5 println(result.get())6}7 println(result.get())8}9 println(result.get())10}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1val json = Gson().toJson(ForceMethod.GET)2FuelManager.instance.baseHeaders = mapOf("X-HTTP-Method-Override" to json)3FuelManager.instance.baseParams = listOf("foo" to "bar")4Fuel.get("/get").responseString { _, _, result ->5println(result)6}7val json = Gson().toJson(ForceMethod.GET)8FuelManager.instance.baseHeaders = mapOf("X-HTTP-Method-Override" to json)9FuelManager.instance.baseParams = listOf("foo" to "bar")10Fuel.get("/get").responseString { _, _, result ->11println(result)12}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1 println(result)2}3 println(result)4}5 println(result)6}7 println(result)8}9 println(result)10}11 println(result)12}13 println(result)14}15 println(result)16}

Full Screen

Full Screen

ForceMethod

Using AI Code Generation

copy

Full Screen

1println(request)2println(response)3println(result)4}5println(request)6println(response)7println(result)8}9println(request)10println(response)11println(result)12}13println(request)14println(response)15println(result)16}17println(request)18println(response)19println(result)20}21println(request)22println(response)23println(result)24}25println(request)26println(response)27println(result)28}29println(request)30println(response)31println(result)32}33println(request)34println(response)35println(result)36}37println(request)38println(response)39println(result)40}41println(request)42println(response)43println(result)44}45println(request)46println(response)47println(result)48}49println(request)50println(response)51println(result)52}

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 ForceMethod

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful