Best Fuel code snippet using com.github.kittinunf.fuel.toolbox.HttpClient
HttpClient.kt
Source:HttpClient.kt
...23import 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....
Deserializable.kt
Source:Deserializable.kt
...16/**17 * Generic interface for [Response] deserialization.18 *19 * @note you are responsible of using the [Response] [Body] [InputStream] and closing it when you're done. Failing to do20 * so can result in hanging connections if used in conjunction with [com.github.kittinunf.fuel.toolbox.HttpClient].21 *22 * @see ResponseDeserializable23 */24interface Deserializable<out T : Any> {25 /**26 * Deserialize [response] into [T]27 *28 * @param response [Response] the incoming response29 * @return [T] the instance of [T]30 */31 fun deserialize(response: Response): T32}33interface ResponseDeserializable<out T : Any> : Deserializable<T> {34 override fun deserialize(response: Response): T {...
HttpClientTest.kt
Source:HttpClientTest.kt
...18import org.mockserver.model.Header.header19import java.io.IOException20import java.io.InputStream21import java.net.HttpURLConnection22class HttpClientTest : MockHttpTestCase() {23 class TestHook : Client.Hook {24 override fun preConnect(connection: HttpURLConnection, request: Request) {25 // no-op26 }27 override fun interpretResponseStream(request: Request, inputStream: InputStream?): InputStream? = inputStream28 override fun postConnect(request: Request) {29 // no-op30 }31 override fun httpExchangeFailed(request: Request, exception: IOException) {32 // no-op33 }34 }35 @Test36 fun httpClientIsTheDefaultClient() {37 val request = Fuel.request(Method.GET, mock.path("default-client"))38 assertThat(request.executionOptions.client, instanceOf(HttpClient::class.java))39 }40 @Test41 fun injectsAcceptTransferEncoding() {42 val request = reflectedRequest(Method.GET, "accept-transfer-encoding")43 val (_, _, result) = request.responseObject(MockReflected.Deserializer())44 val (data, error) = result45 assertThat("Expected data, actual error $error", data, notNullValue())46 assertThat(data!![Headers.ACCEPT_TRANSFER_ENCODING].size, not(equalTo(0)))47 }48 @Test49 fun setsContentLengthIfKnownZero() {50 val request = reflectedRequest(Method.POST, "content-length-test")51 .body("")52 val (_, _, result) = request.responseObject(MockReflected.Deserializer())53 val (data, error) = result54 assertThat("Expected data, actual error $error", data, notNullValue())55 assertThat(data!![Headers.CONTENT_LENGTH].firstOrNull(), equalTo("0"))56 }57 @Test58 fun setsContentLengthIfKnownNonZero() {59 val request = reflectedRequest(Method.POST, "content-length-test")60 .body("my-body")61 val (_, _, result) = request.responseObject(MockReflected.Deserializer())62 val (data, error) = result63 assertThat("Expected data, actual error $error", data, notNullValue())64 assertThat(data!![Headers.CONTENT_LENGTH].firstOrNull(), equalTo("my-body".toByteArray().size.toString()))65 }66 @Test67 fun dropBodyForGetRequest() {68 val request = reflectedRequest(Method.GET, "get-body-output")69 .body("my-body")70 val (_, _, result) = request.responseObject(MockReflected.Deserializer())71 val (data, error) = result72 assertThat("Expected data, actual error $error", data, notNullValue())73 assertThat(data!!.body, nullValue())74 }75 @Test76 fun allowPostWithBody() {77 val request = reflectedRequest(Method.POST, "post-body-output")78 .body("my-body")79 val (_, _, result) = request.responseObject(MockReflected.Deserializer())80 val (data, error) = result81 assertThat("Expected data, actual error $error", data, notNullValue())82 assertThat(data!!.body!!.string, equalTo("my-body"))83 }84 @Test85 fun usesOverrideMethodForPatch() {86 val request = Fuel.patch(mock.path("patch-with-override"))87 mock.chain(88 request = mock.request().withMethod(Method.POST.value).withPath("/patch-with-override"),89 response = mock.reflect()90 )91 val (_, _, result) = request.responseObject(MockReflected.Deserializer())92 val (data, error) = result93 assertThat("Expected data, actual error $error", data, notNullValue())94 assertThat(data!!.method, equalTo(Method.POST.value))95 assertThat(data["X-HTTP-Method-Override"].firstOrNull(), equalTo(Method.PATCH.value))96 }97 @Test98 fun allowPatchWithBody() {99 val manager = FuelManager()100 manager.forceMethods = true101 assertThat(manager.forceMethods, equalTo(true))102 val request = manager.request(Method.PATCH, mock.path("patch-body-output"))103 .body("my-body")104 assertThat(request.executionOptions.forceMethods, equalTo(true))105 mock.chain(106 request = mock.request().withMethod(Method.PATCH.value).withPath("/patch-body-output"),107 response = mock.reflect()108 )109 val (_, _, result) = request.responseObject(MockReflected.Deserializer())110 val (data, error) = result111 assertThat("Expected data, actual error $error", data, notNullValue())112 assertThat(data!!.body!!.string, equalTo("my-body"))113 assertThat(data.method, equalTo(Method.PATCH.value))114 assert(data["X-HTTP-Method-Override"].isNullOrEmpty())115 }116 @Test117 fun allowDeleteWithBody() {118 val request = reflectedRequest(Method.DELETE, "delete-body-output")119 .body("my-body")120 val (_, _, result) = request.responseObject(MockReflected.Deserializer())121 val (data, error) = result122 assertThat("Expected data, actual error $error", data, notNullValue())123 assertThat(data!!.body!!.string, equalTo("my-body"))124 }125 @Test126 fun canDisableClientCache() {127 mock.chain(128 request = mock.request()129 .withMethod(Method.GET.value)130 .withPath("/cached"),131 response = mock.response()132 .withHeader(Headers.CACHE_CONTROL, "max-age=600")133 .withBody("cached"),134 times = Times.once()135 )136 mock.chain(137 request = mock.request()138 .withMethod(Method.GET.value)139 .withPath("/cached")140 .withHeader(header(Headers.CACHE_CONTROL, "no-cache")),141 response = mock.response()142 .withHeader(Headers.CACHE_CONTROL, "max-age=600")143 .withBody("fresh"),144 times = Times.once()145 )146 val request = Fuel.get(mock.path("cached"))147 val (_, _, result) = request.responseString()148 val (data, error) = result149 assertThat("Expected data, actual error $error", data, notNullValue())150 assertThat(data, equalTo("cached"))151 val (_, _, result2) = request.apply { executionOptions.useHttpCache = false }.responseString()152 val (data2, error2) = result2153 assertThat("Expected data, actual error $error2", data2, notNullValue())154 assertThat(data2, equalTo("fresh"))155 }156 @Test157 fun changeClientHook() {158 val request = Fuel.request(Method.GET, mock.path("change-hook")).apply {159 val httpClient = executionOptions.client as HttpClient160 httpClient.hook = TestHook()161 }162 val client = request.executionOptions.client as HttpClient163 assertThat(client.hook, instanceOf(TestHook::class.java))164 }165}...
FuelManager.kt
Source:FuelManager.kt
1package com.github.kittinunf.fuel.core2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.interceptors.redirectResponseInterceptor4import com.github.kittinunf.fuel.core.interceptors.validatorResponseInterceptor5import com.github.kittinunf.fuel.toolbox.HttpClient6import com.github.kittinunf.fuel.util.SameThreadExecutorService7import com.github.kittinunf.fuel.util.readWriteLazy8import java.net.Proxy9import java.security.KeyStore10import java.util.concurrent.Executor11import java.util.concurrent.ExecutorService12import java.util.concurrent.Executors13import javax.net.ssl.HostnameVerifier14import javax.net.ssl.HttpsURLConnection15import javax.net.ssl.SSLContext16import javax.net.ssl.SSLSocketFactory17import javax.net.ssl.TrustManagerFactory18class FuelManager {19 var client: Client by readWriteLazy { HttpClient(proxy) }20 var proxy: Proxy? = null21 var basePath: String? = null22 var baseHeaders: Map<String, String>? = null23 var baseParams: List<Pair<String, Any?>> = emptyList()24 var keystore: KeyStore? = null25 var socketFactory: SSLSocketFactory by readWriteLazy {26 keystore?.let {27 val trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())28 trustFactory.init(it)29 val sslContext = SSLContext.getInstance("SSL")30 sslContext.init(null, trustFactory.trustManagers, null)31 sslContext.socketFactory32 } ?: HttpsURLConnection.getDefaultSSLSocketFactory()33 }...
CustomHttpClient.kt
Source:CustomHttpClient.kt
...39 * This class can be removed when either GitHub supports the `X-HTTP-Method-Override`, which is the recommended40 * solution for dealing with the missing PATCH HTTP verb in [HttpsURLConnection], or when [HttpsURLConnection] gets41 * support for PATCH.42 *43 * This class is a copy of [com.github.kittinunf.fuel.toolbox.HttpClient], with the check/replace for PATCH requests44 * removed.45 */46@Service47@Suppress("TooGenericExceptionCaught", "SwallowedException") // Expected behavior48internal class CustomHttpClient(private val proxy: Proxy? = null) : Client {49 init {50 allowMethods("PATCH")51 }52 override fun executeRequest(request: Request): Response {53 val connection = establishConnection(request) as? HttpURLConnection54 ?: throw IllegalStateException("Connection invalid.")55 try {56 connection.apply {57 connectTimeout = request.timeoutInMillisecond58 readTimeout = request.timeoutReadInMillisecond59 doInput = true60 useCaches = false61 requestMethod = request.method.value62 instanceFollowRedirects = false...
MockHttpClient.kt
Source:MockHttpClient.kt
1package com.rpmtw.rpmtw_api_client.mock2import com.github.kittinunf.fuel.core.*3import com.github.kittinunf.fuel.core.requests.DefaultBody4import com.github.kittinunf.fuel.toolbox.HttpClient5import com.google.gson.Gson6import com.google.gson.JsonElement7import java.io.ByteArrayInputStream8class MockHttpClient {9 companion object {10 fun mockRequest(response: MockHttpResponse, gson: Gson = Gson()) {11 val httpClient = object : Client {12 @Suppress("LiftReturnOrAssignment")13 override fun executeRequest(request: Request): Response {14 val body: Body15 val data: Any? = response.data16 if (data != null) {17 if (data is JsonElement) {18 body = DefaultBody({ ByteArrayInputStream(gson.toJson(data).toByteArray()) })19 } else {20 body = DefaultBody({21 ByteArrayInputStream(22 "{\"data\":${gson.toJson(response.data)}}".toByteArray()23 )24 })25 }26 } else {27 body = DefaultBody()28 }29 FuelManager.instance.client =30 HttpClient(hook = FuelManager.instance.hook, proxy = FuelManager.instance.proxy)31 return Response(32 body = body,33 statusCode = response.statusCode,34 responseMessage = response.responseMessage,35 url = request.url36 )37 }38 }39 FuelManager.instance.client = httpClient40 }41 }42}...
HttpClient
Using AI Code Generation
1import com.github.kittinunf.fuel.Fuel2fun main(args: Array<String>) {3 println(request)4 println(response)5 println(result)6}7{ "args": {}, "headers": { "Accept-Encoding": "identity", "Host": "httpbin.org", "User-Agent": "Fuel/1.12.0" }, "origin": "
HttpClient
Using AI Code Generation
1 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")2 FuelManager.instance.baseParams = listOf("access_token" to "1234")3 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")4 FuelManager.instance.baseParams = listOf("access_token" to "1234")5 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")6 FuelManager.instance.baseParams = listOf("access_token" to "1234")7 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")8 FuelManager.instance.baseParams = listOf("access_token" to "1234")9 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")10 FuelManager.instance.baseParams = listOf("access_token" to "1234")11 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")12 FuelManager.instance.baseParams = listOf("access_token" to "1234")13 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")14 FuelManager.instance.baseParams = listOf("access_token" to "1234")15 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")16 FuelManager.instance.baseParams = listOf("access_token" to "1234")17 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")18 FuelManager.instance.baseParams = listOf("access_token" to "1234")19 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Fuel")20 FuelManager.instance.baseParams = listOf("access_token" to "1234")
HttpClient
Using AI Code Generation
1val (user, error) = result2if (user != null) {3println(user)4} else {5println(error)6}7}8println(response)9}10println(response)11}12val (bytes, error) = result13if (bytes != null) {14println(bytes)15} else {16println(error)17}18}19val (bytes, error) = result20if (bytes != null) {21println(bytes)22} else {23println(error)24}25}26val (bytes, error) = result27if (bytes != null) {28println(bytes)29} else {30println(error)31}32}33val (bytes, error) = result34if (bytes != null) {35println(bytes)36} else {37println(error)38}39}40val (bytes, error) = result41if (bytes != null) {42println(bytes)43} else {44println(error)45}46}47val (bytes, error) = result48if (bytes != null) {49println(bytes)50} else {51println(error)52}53}54val (bytes, error) = result55if (bytes != null) {56println(bytes)57} else {58println(error)59}60}
HttpClient
Using AI Code Generation
1connection.outputStream.use { it.write("foo=bar".toByteArray()) }2println(String(connection.inputStream.readBytes()))3val client = HttpClientBuilder.create().build()4post.entity = UrlEncodedFormEntity(listOf(BasicNameValuePair("foo", "bar")))5val response = client.execute(post)6println(EntityUtils.toString(response.entity))7val client = OkHttpClient()8val body = FormBody.Builder()9.add("foo", "bar")10.build()11val request = Request.Builder()12.post(body)13.build()14val response = client.newCall(request).execute()15println(response.body()?.string())
HttpClient
Using AI Code Generation
1val (request, response, result) = Fuel.get("/").responseString()2val (request, response, result) = Fuel.get("/").responseString()3val (request, response, result) = Fuel.get("/").responseString()4val (request, response, result) = Fuel.get("/").responseString()5val (request, response, result) = Fuel.get("/").responseString()6val (request, response, result) = Fuel.get("/").responseString()7val (request, response, result) = Fuel.get("/").responseString()8val (request, response, result) = Fuel.get("/").responseString()9val (request, response, result) = Fuel.get("/").responseString()10val (request, response, result) = Fuel.get("/").responseString()
HttpClient
Using AI Code Generation
1import com.github.kittinunf.fuel.httpGet2import com.github.kittinunf.result.Result3fun main(args: Array<String>) {4 url.httpGet().responseString { request, response, result ->5 when (result) {6 is Result.Failure -> {7 val ex = result.getException()8 println(ex)9 }10 is Result.Success -> {11 val data = result.get()12 println(data)13 }14 }15 }16}17import com.github.kittinunf.fuel.Fuel18import com.github.kittinunf.result.Result19fun main(args: Array<String>) {20 Fuel.get(url).responseString { request, response, result ->21 when (result) {22 is Result.Failure -> {23 val ex = result.getException()24 println(ex)25 }26 is Result.Success -> {27 val data = result.get()28 println(data)29 }30 }31 }32}33import com.github.kittinunf.fuel.httpPost34import com.github.kittinunf.result.Result35fun main(args: Array<String>) {36 val parameters = listOf("key1" to "value1", "key2" to "value2")37 url.httpPost(parameters).responseString { request, response, result ->38 when (result) {39 is Result.Failure -> {40 val ex = result.getException()41 println(ex)42 }43 is Result.Success -> {44 val data = result.get()45 println(data)46 }47 }48 }49}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!