Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.internal
Deserializable.kt
Source:Deserializable.kt
...143 * Deserialize the [Response] to the [this] into a [T] using [U]144 *145 * @note not async, use the variations with a handler instead.146 *147 * @throws Exception if there is an internal library error, not related to Network or Deserialization148 *149 * @param deserializable [U] the instance that performs deserialization150 * @return [ResponseResultOf<T>] the response result of151 */152fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U): ResponseResultOf<T> {153 // First execute the network request and catch any issues154 val rawResponse = runCatching { toTask().call() }155 .onFailure { error ->156 FuelError.wrap(error, Response.error(url)).also {157 return Triple(this, it.response, Result.error(it))158 }159 }160 .getOrThrow()161 // By this time it should have a response, but deserialization might fail162 return runCatching { Triple(this, rawResponse, Result.Success(deserializable.deserialize(rawResponse))) }163 .recover { error -> Triple(this, rawResponse, Result.Failure(FuelError.wrap(error, rawResponse))) }164 .getOrThrow()165}166/**167 * Ignore the response result168 *169 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]170 * to a large download and without using the result [ByteArray]171 *172 * @see [com.github.kittinunf.fuel.core.Request.response]173 *174 * @note not async, use the variations with a handler instead.175 *176 * @throws Exception if there is an internal library error, not related to Network177 */178fun Request.responseUnit(): ResponseResultOf<Unit> = response(EmptyDeserializer)179private fun <T : Any, U : Deserializable<T>> Request.response(180 deserializable: U,181 success: (Request, Response, T) -> Unit,182 failure: (Request, Response, FuelError) -> Unit183): CancellableRequest {184 val asyncRequest = RequestTaskCallbacks(185 request = this,186 onSuccess = { response ->187 // The network succeeded but deserialization might fail188 val deliverable = Result.of<T, Exception> { deserializable.deserialize(response) }189 executionOptions.callback {190 deliverable.fold(...
Request.kt
Source:Request.kt
...80 }81 return this82 }83 fun header(pairs: Map<String, Any>?): Request = header(pairs, true)84 internal fun header(pairs: Map<String, Any>?, replace: Boolean): Request {85 pairs?.forEach {86 it.let {87 if (!httpHeaders.containsKey(it.key) || replace) {88 httpHeaders.plusAssign(Pair(it.key, it.value.toString()))89 }90 }91 }92 return this93 }94 fun body(body: ByteArray): Request {95 bodyCallback = { request, outputStream, totalLength ->96 outputStream?.write(body)97 body.size.toLong()98 }...
ProxyListener.kt
Source:ProxyListener.kt
...4import com.github.kittinunf.fuel.core.requests.write5import com.github.kittinunf.fuel.core.requests.writeln6import com.github.salomonbrys.kotson.fromJson7import com.google.gson.Gson8import com.sun.org.apache.xpath.internal.operations.Bool9import javax.swing.JToggleButton10import javax.swing.JTextField11class ProxyListener(private val requestHookField: JTextField, private val responseHookField: JTextField,12 private val requestHookButton: JToggleButton, private val responseHookButton: JToggleButton,13 private val callbacks: IBurpExtenderCallbacks): IProxyListener {14 override fun processProxyMessage(messageIsRequest: Boolean, message: IInterceptedProxyMessage) {15 val requestHookURL = requestHookField.text16 val responseHookURL = responseHookField.text17 val httpRequestResponse = message.messageInfo18 val messageReference = message.messageReference19 val gson = Gson()20 FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json")21 val b2b = BurpToBuddy(callbacks)22 if (!requestHookButton.isSelected && messageIsRequest && requestHookURL != "") {...
HTTP.kt
Source:HTTP.kt
...23 fun cancel() {24 request.cancel()25 }26}27internal class HTTP {28 sealed class Result {29 class Success(val data: String) : Result()30 open class Error(open val exception: Exception) : Result()31 class HttpError(override val exception: Exception, val statusCode: Int) : Error(exception)32 }33 private val baseUrlSnapshot = mapOf(34 ViewType.LIST to Constants.BASE_URL_LIST_SNAPSHOT,35 ViewType.MAP to Constants.BASE_URL_MAP_SNAPSHOT36 )37 private val baseUrlEntity = mapOf(38 ViewType.LIST to Constants.BASE_URL_LIST_SNAPSHOT,39 ViewType.MAP to Constants.BASE_URL_MAP_SNAPSHOT40 )41 internal fun request(tag: String?, entityTypes: List<EntityType>, region: VDBounds?, zoom: Int?, viewType: ViewType, apiKey: String, onCompletion: (result: Result) -> Unit): VDRequest {42 val url = buildUrl(tag, entityTypes, region, zoom, viewType, apiKey)43 return request(url, onCompletion)44 }45 private fun request(url: String, onCompletion: (result: Result) -> Unit): VDRequest {46 val httpRequest = url.httpGet()47 .interrupt { request -> println("${request.url} was interrupted and cancelled") }48 .response { request, response, result ->49 if (!request.isCancelled) {50 when (result) {51 is FuelResult.Failure -> {52 onCompletion(Result.HttpError(result.error, response.statusCode))53 }54 is FuelResult.Success -> {55 onCompletion(Result.Success(String(result.value)))...
FuelClient.kt
Source:FuelClient.kt
...7import com.github.kittinunf.fuel.gson.jsonBody8import com.touki.otopost.common.result.CommonResult9import com.touki.otopost.common.result.HttpError10import java.io.InputStream11internal class FuelClient: HttpClient {12 private lateinit var requestClient : Request13 override fun post(url : String) = apply {14 requestClient = Fuel.post(url)15 }16 override fun get(url : String) = apply {17 requestClient = Fuel.get(url)18 }19 override fun delete(url: String) = apply {20 requestClient = Fuel.delete(url)21 }22 override fun put(url: String) = apply {23 requestClient = Fuel.put(url)24 }25 override fun download(url: String) = apply {...
RequestTask.kt
Source:RequestTask.kt
...8private typealias RequestTaskResult = Pair<Request, Response>9/**10 * Synchronous version of [SuspendableRequest]. Turns a [Request] into a [Callable]11 */12internal class RequestTask(internal val request: Request) : Callable<Response> {13 private val interruptCallback by lazy { executor.interruptCallback }14 private val executor by lazy { request.executionOptions }15 private val client by lazy { executor.client }16 private fun prepareRequest(request: Request): Request = executor.requestTransformer(request)17 @Throws(FuelError::class)18 private fun executeRequest(request: Request): RequestTaskResult {19 return runCatching { Pair(request, client.executeRequest(request)) }20 .recover { error -> throw FuelError.wrap(error, Response(request.url)) }21 .getOrThrow()22 }23 @Throws(FuelError::class)24 private fun prepareResponse(result: RequestTaskResult): Response {25 val (request, response) = result26 return runCatching { executor.responseTransformer(request, response) }27 .mapCatching { transformedResponse ->28 val valid = executor.responseValidator(transformedResponse)29 if (valid) transformedResponse30 else throw FuelError.wrap(HttpException(transformedResponse.statusCode, transformedResponse.responseMessage), transformedResponse)31 }32 .recover { error -> throw FuelError.wrap(error, response) }33 .getOrThrow()34 }35 @Throws(FuelError::class)36 override fun call(): Response {37 return runCatching { prepareRequest(request) }38 .mapCatching { executeRequest(it) }39 .mapCatching { pair ->40 // Nested runCatching so response can be rebound41 runCatching { prepareResponse(pair) }42 .recover { error ->43 error.also { Fuel.trace { "[RequestTask] execution error\n\r\t$error" } }44 throw FuelError.wrap(error, pair.second)45 }46 .getOrThrow()47 }48 .onFailure { error ->49 Fuel.trace { "[RequestTask] on failure (interrupted=${(error as? FuelError)?.causedByInterruption ?: error})" }50 if (error is FuelError && error.causedByInterruption) {51 Fuel.trace { "[RequestTask] execution error\n\r\t$error" }52 interruptCallback.invoke(request)53 }54 }55 .getOrThrow()56 }57}58internal fun Request.toTask(): Callable<Response> = RequestTask(this)...
Helpers.kt
Source:Helpers.kt
...12import java.nio.charset.StandardCharsets13import java.util.Stack14import java.util.concurrent.CompletableFuture15import java.util.concurrent.Future16internal fun mockHttpClient(vararg jsonResponses: JSONObject, code: Int = 200): List<Pair<Future<Request>, Response>> {17 val responses = jsonResponses.map { json ->18 mock<Response> {19 on { statusCode } doReturn code20 on { dataStream } doReturn ByteArrayInputStream(json.toString().toByteArray())21 }22 }23 val requestsAndResponses = responses.map { CompletableFuture<Request>() to it }24 val requestsAndResponsesStack = Stack<Pair<CompletableFuture<Request>, Response>>().apply {25 addAll(requestsAndResponses.asReversed())26 }27 FuelConfiguration(mock {28 on { executeRequest(any()) } doAnswer { answer ->29 val (request, response) = requestsAndResponsesStack.pop()30 request.complete(answer.getArgument(0))31 response32 }33 })34 return requestsAndResponses35}36internal fun Request.bodyContents() = ByteArrayOutputStream().let { outputStream ->37 bodyCallback?.invoke(request, outputStream, 0)38 String(outputStream.toByteArray(), StandardCharsets.UTF_8)39}...
RequestTaskCallbacks.kt
Source:RequestTaskCallbacks.kt
...3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import java.util.concurrent.Callable7internal typealias RequestSuccessCallback = ((Response) -> Unit)8internal typealias RequestFailureCallback = ((FuelError, Response) -> Unit)9/**10 * Wraps a [task] with callbacks [onSuccess] and [onFailure]11 *12 * @param request [Request] the request that generated the task13 * @param task [Callable<Response>] the task to execute (and perform callbacks on)14 * @param onSuccess [RequestSuccessCallback] the success callback, called when everything went fine15 * @param onFailure [RequestFailureCallback] the failure callback, called when an error occurred16 */17internal class RequestTaskCallbacks(18 private val request: Request,19 private val task: Callable<Response> = request.toTask(),20 private val onSuccess: RequestSuccessCallback,21 private val onFailure: RequestFailureCallback22) : Callable<Response> {23 override fun call(): Response {24 Fuel.trace { "[RequestTaskCallbacks] start request task\n\r\t$request" }25 return runCatching { task.call() }26 .mapCatching { it -> it.also { onSuccess(it) } }27 .getOrElse { error -> FuelError.wrap(error).also { onFailure(it, it.response) }.response }28 }29}...
internal
Using AI Code Generation
1+import com.github.kittinunf.fuel.core.requests.HttpRequest2+import com.github.kittinunf.fuel.core.requests.HttpRequestBuilder3+import com.github.kittinunf.fuel.core.requests.HttpRequestExecutor4+import com.github.kittinunf.fuel.core.requests.HttpRequest5+import com.github.kittinunf.fuel.core.requests.HttpRequestBuilder6+import com.github.kittinunf.fuel.core.requests.HttpRequestExecutor7+import com.github.kittinunf.fuel.core.requests.HttpRequest8+import com.github.kittinunf.fuel.core.requests.HttpRequestBuilder9+import com.github.kittinunf.fuel.core.requests.HttpRequestExecutor10+import com.github.kittinunf.fuel.core.requests.HttpRequest11+import com.github.kittinunf.fuel.core.requests.HttpRequestBuilder12+import com.github.kittinunf.fuel.core.requests.HttpRequestExecutor13+import com.github.kittinunf.fuel.core.requests.HttpRequest14+import com.github.kittinunf.fuel.core.requests.HttpRequestBuilder15+import com.github.kittinunf.fuel.core.requests.HttpRequestExecutor16+import com.github.kittinunf.fuel.core.requests.HttpRequest17+import com.github.kittinunf.fuel.core.requests.HttpRequestBuilder18+import com.github.kittinunf.fuel.core.requests.HttpRequestExecutor19+import com.github.kittinunf.fuel.core.requests.HttpRequest20+import com.github.kittinunf.fuel.core.requests.HttpRequestBuilder21+import com.github.kittinunf.fuel.core.requests.HttpRequestExecutor
internal
Using AI Code Generation
1+internal fun Request.url() = url2+internal fun Request.headers() = headers3+internal fun Request.method() = method4+internal fun Request.body() = body5+internal fun Request.parameters() = parameters6+internal fun Request.timeout() = timeout7+internal fun Request.timeoutRead() = timeoutRead8+internal fun Request.timeoutWrite() = timeoutWrite9+internal fun Request.followRedirects() = followRedirects10+internal fun Request.responseType() = responseType11+internal fun Request.userAgent() = userAgent12+internal fun Request.authentication() = authentication13+internal fun Request.proxy() = proxy14+internal fun Request.progress() = progress15+internal fun Request.responseValidator() = responseValidator16+internal fun Request.responseInterceptor() = responseInterceptor17+internal fun Request.requestInterceptor() = requestInterceptor18+internal fun Request.cUrl() = cUrl19+internal fun Request.cUrlString() = cUrlString20+internal fun Request.cUrlStringFormatted() = cUrlStringFormatted21+internal fun Request.cUrlCommand() = cUrlCommand22+internal fun Request.cUrlCommandFormatted() = cUrlCommandFormatted23+internal fun Request.cUrlCommandString() = cUrlCommandString24+internal fun Request.cUrlCommandStringFormatted() = cUrlCommandStringFormatted25+internal fun Request.cUrlRequest() = cUrlRequest26+internal fun Request.cUrlRequestFormatted() = cUrlRequestFormatted27+internal fun Request.cUrlRequestString() = cUrlRequestString28+internal fun Request.cUrlRequestStringFormatted() = cUrlRequestStringFormatted29+internal fun Request.cUrlResponse() = cUrlResponse30+internal fun Request.cUrlResponseFormatted() = cUrlResponseFormatted31+internal fun Request.cUrlResponseString() = cUrlResponseString32+internal fun Request.cUrlResponseStringFormatted() = cUrlResponseStringFormatted33+internal fun Request.cUrlResponseStream() = cUrlResponseStream34+internal fun Request.cUrlResponseStreamFormatted() = cUrlResponseStreamFormatted35+internal fun Request.cUrlResponseStreamString() = cUrlResponseStreamString36+internal fun Request.cUrlResponseStreamStringFormatted() = cUrlResponseStreamStringFormatted37+internal fun Request.cUrlResponseStreamStringFormattedWithColor() = cUrlResponseStreamStringFormattedWithColor38+internal fun Request.cUrlResponseStreamStringFormattedWithColorAndHeaders() = cUrlResponseStream
internal
Using AI Code Generation
1class DefaultBody : Body {2 override fun toByteArray(): ByteArray {3 return byteArrayOf()4 }5}6class DefaultRequest : Request {7 get() = Method.GET8 get() = listOf()9 get() = mapOf()10 get() = null11}12class HttpClient : Client {13 override fun executeRequest(request: Request): Response {14 return Response()15 }16}17fun main() {18 val request = DefaultRequest()19 val client = HttpClient()20 val (response, result) = client.executeRequest(request)21 println(response)22 println(result)23}24 at com.github.kittinunf.fuel.core.ClientKt.executeRequest(Client.kt)25 at com.github.kittinunf.fuel.core.ClientKt.executeRequest$default(Client.kt:15)26 at com.github.kittinunf.fuel.core.ClientKt.executeRequest(Client.kt:15)27 at com.github.kittinunf.fuel.core.ClientKt.executeRequest$default(Client.kt:15)28 at com.github.kittinunf.fuel.core.ClientKt.executeRequest(Client.kt:15)29 at com.github.kittinunf.fuel.core.ClientKt.executeRequest$default(Client.kt:15)30 at com.github.kittinunf.fuel.core.ClientKt.executeRequest(Client.kt:15)31 at com.github.kittinunf.fuel.core.ClientKt.executeRequest$default(Client.kt
internal
Using AI Code Generation
1 val request: Request = Request()2 request.headers = mapOf("Content-Type" to "application/json")3 request.body = """ { "hello": "world" } """.toByteArray()4 request.response { result ->5 when (result) {6 is Result.Success -> {7 val data = result.get()8 Log.d("Fuel", "Success ${data.content}")9 }10 is Result.Failure -> {11 Log.d("Fuel", "Failure ${result.error}")12 }13 }14 }15 val task: Task = Task()16 task.response = { result ->17 when (result) {18 is Result.Success -> {19 val data = result.get()20 Log.d("Fuel", "Success ${data.content}")21 }22 is Result.Failure -> {23 Log.d("Fuel", "Failure ${result.error}")24 }25 }26 }27 FuelManager.instance.executor.execute(task)28}
internal
Using AI Code Generation
1 val requestUrl = fuelRequest.url.toString()2 val responseUrl = response.url.toString()3 val responseString = result.get()4 val responseJson = result.get().jsonObject5 val responseXml = result.get().xml6 val responseBytes = result.get().bytes7 val responseFile = result.get().file8 val responseStream = result.get().stream
internal
Using AI Code Generation
1var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {2}.response()3var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {4}.response()5var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {6}.response()7var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {8}.response()9var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {10}.response()11var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {12}.response()13var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {14}.response()15var response = com.github.kittinunf.fuel.core.requests.DefaultRequest().apply {
internal
Using AI Code Generation
1public static class Request {2 public static String getMethod(Request request) {3 return request.method;4 }5}6public static String getMethod(Request request) {7 return request.method;8}9public static String getMethod(Request request) {10 try {11 Class<?> cls = Class.forName("com.github.kittinunf.fuel.core.requests.Request");12 Field field = cls.getDeclaredField("method");13 field.setAccessible(true);14 return (String) field.get(request);15 } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {16 throw new RuntimeException(e);17 }18}
internal
Using AI Code Generation
1+class FuelManagerForTests : FuelManager() {2+ fun requestForTests(method: Method, path: String, parameters: List<Pair<String, Any?>> = listOf()): Request {3+ return request(method, path, parameters)4+ }5+}6+class FuelRequestTest : Spek({7+ given("FuelRequest") {8+ val manager = FuelManagerForTests()9+ on("toString") {10+ val result = request.toString()11+ it("should return string representation of request") {12+ }13+ }14+ }15+})16 import com.github.kittinunf.fuel.core.requests.cUrlString17 import com.github.kittinunf.fuel.core.requests.httpBin18@@ -13,6 +13,7 @@ import org.hamcrest.CoreMatchers.equalTo19 import org.hamcrest.CoreMatchers.not20 import org.hamcrest.CoreMatchers.notNullValue21 import org.hamcrest.MatcherAssert.assertThat22+import org.hamcrest.Matchers.containsString23 import org.junit.Assert.assertEquals24 import org.junit.Assert.assertFalse25 import org.junit.Assert.assertTrue26@@ -22,7 +23,7 @@ import org.junit.Test27 class RequestsTest : BaseTestCase() {28- fun httpBinGet() {29+ fun httpBinGetAsString() {30 val (_, _, result) = http
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!!