How to use HttpURLConnection.forceMethod method of com.github.kittinunf.fuel.toolbox.extensions.ForceMethod class

Best Fuel code snippet using com.github.kittinunf.fuel.toolbox.extensions.ForceMethod.HttpURLConnection.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

1package com.github.kittinunf.fuel.toolbox.extensions2import com.github.kittinunf.fuel.core.Method3import com.github.kittinunf.fuel.test.MockHttpTestCase4import org.hamcrest.CoreMatchers.equalTo5import 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)24 assertThat(httpUrlConnection.requestMethod, equalTo(Method.POST.value))25 }26 @Test27 fun forceHttpsPatchMethod() {28 val connection = URL(this.mock.securedPath("secured-force-patch-test")).openConnection()29 assert(connection is HttpURLConnection)30 val httpUrlConnection = connection as HttpURLConnection31 httpUrlConnection.forceMethod(Method.PATCH)32 assertThat(httpUrlConnection.requestMethod, equalTo(Method.PATCH.value))33 }34 @Test35 fun forceHttpsPostMethod() {36 val connection = URL(this.mock.securedPath("secured-force-post-test")).openConnection()37 assert(connection is HttpURLConnection)38 val httpUrlConnection = connection as HttpURLConnection39 httpUrlConnection.forceMethod(Method.POST)40 assertThat(httpUrlConnection.requestMethod, equalTo(Method.POST.value))41 }42}...

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

HttpURLConnection.forceMethod

Using AI Code Generation

copy

Full Screen

1}2}3}4}5}6}7}8}9}10}11}12}13}14}

Full Screen

Full Screen

HttpURLConnection.forceMethod

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.core.*2import com.github.kittinunf.fuel.toolbox.extensions.ForceMethod3import java.net.HttpURLConnection4fun main() {5 .httpPatch()6 .forceMethod(HttpURLConnection::class.java, "PATCH")7 .responseString()8 println(request)9 println(response)10 println(result)11}

Full Screen

Full Screen

HttpURLConnection.forceMethod

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.core.FuelManager2import com.github.kittinunf.fuel.toolbox.extensions.ForceMethod3import java.net.HttpURLConnection4FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")5ForceMethod(HttpURLConnection.HTTP_POST).let {6 FuelManager.instance.baseInterceptors.add(it)7}8FuelManager.instance.request(Method.POST, "/api/endpoint").response { request, response, result ->9}10import com.github.kittinunf.fuel.core.FuelManager11import com.github.kittinunf.fuel.toolbox.extensions.ForceMethod12import java.net.HttpURLConnection13FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")14ForceMethod(HttpURLConnection.HTTP_POST).let {15 FuelManager.instance.baseInterceptors.add(it)16}17FuelManager.instance.request(Method.POST, "/api/endpoint").response { request, response, result ->18}19import com.github.kittinunf.fuel.core.FuelManager20import com.github.kittinunf.fuel.toolbox.extensions.ForceMethod21import java.net.HttpURLConnection22FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")

Full Screen

Full Screen

HttpURLConnection.forceMethod

Using AI Code Generation

copy

Full Screen

1 .source { _, _ -> File("path/to/file") }2 .forceMethod("PUT")3 .response()4 .source { _, _ -> File("path/to/file") }5 .setFixedLengthStreamingMode()6 .response()7 .source { _, _ -> File("path/to/file") }8 .setChunkedStreamingMode(1024)9 .response()10 .source { _, _ -> File("path/to/file") }11 .setChunkedStreamingMode(1024)12 .response()13 .source { _, _ -> File("path/to

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 method 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