Best Fuel code snippet using com.github.kittinunf.fuel.Fuel.String.httpGet
FuelHttpUnitTest.kt
Source:FuelHttpUnitTest.kt
1package com.baeldung.fuel2import awaitObjectResult3import awaitStringResponse4import com.github.kittinunf.fuel.Fuel5import com.github.kittinunf.fuel.core.FuelManager6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor8import com.github.kittinunf.fuel.gson.responseObject9import com.github.kittinunf.fuel.httpGet10import com.github.kittinunf.fuel.rx.rx_object11import com.google.gson.Gson12import kotlinx.coroutines.experimental.runBlocking13import org.junit.jupiter.api.Assertions14import org.junit.jupiter.api.Test15import java.io.File16import java.util.concurrent.CountDownLatch17internal class FuelHttpUnitTest {18 @Test19 fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {20 val latch = CountDownLatch(1)21 "http://httpbin.org/get".httpGet().response{22 request, response, result ->23 val (data, error) = result24 Assertions.assertNull(error)25 Assertions.assertNotNull(data)26 Assertions.assertEquals(200,response.statusCode)27 latch.countDown()28 }29 latch.await()30 }31 @Test32 fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {33 val (request, response, result) = "http://httpbin.org/get".httpGet().response()34 val (data, error) = result35 Assertions.assertNull(error)36 Assertions.assertNotNull(data)37 Assertions.assertEquals(200,response.statusCode)38 }39 @Test40 fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {41 val (request, response, result) =42 "https://jsonplaceholder.typicode.com/posts"43 .httpGet(listOf("id" to "1")).response()44 val (data, error) = result45 Assertions.assertNull(error)46 Assertions.assertNotNull(data)47 Assertions.assertEquals(200,response.statusCode)48 }49 @Test50 fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {51 val latch = CountDownLatch(1)52 Fuel.post("http://httpbin.org/post").response{53 request, response, result ->54 val (data, error) = result55 Assertions.assertNull(error)56 Assertions.assertNotNull(data)57 Assertions.assertEquals(200,response.statusCode)58 latch.countDown()59 }60 latch.await()61 }62 @Test63 fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {64 val (request, response, result) = Fuel.post("http://httpbin.org/post").response()65 val (data, error) = result66 Assertions.assertNull(error)67 Assertions.assertNotNull(data)68 Assertions.assertEquals(200,response.statusCode)69 }70 @Test71 fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() {72 val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")73 .body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}")74 .response()75 val (data, error) = result76 Assertions.assertNull(error)77 Assertions.assertNotNull(data)78 Assertions.assertEquals(201,response.statusCode)79 }80 @Test81 fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {82 FuelManager.instance.basePath = "http://httpbin.org"83 FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra")84 FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())85 FuelManager.instance.addRequestInterceptor(tokenInterceptor())86 val (request, response, result) = "/get"87 .httpGet().response()88 val (data, error) = result89 Assertions.assertNull(error)90 Assertions.assertNotNull(data)91 Assertions.assertEquals(200,response.statusCode)92 }93 @Test94 fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() {95 FuelManager.instance.basePath = "http://httpbin.org"96 FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor())97 FuelManager.instance.addRequestInterceptor(tokenInterceptor())98 val (request, response, result) = "/get"99 .httpGet().response()100 val (data, error) = result101 Assertions.assertNull(error)102 Assertions.assertNotNull(data)103 Assertions.assertEquals(200,response.statusCode)104 }105 @Test106 fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {107 Fuel.download("http://httpbin.org/bytes/32768").destination { response, url ->108 File.createTempFile("temp", ".tmp")109 }.response{110 request, response, result ->111 val (data, error) = result112 Assertions.assertNull(error)113 Assertions.assertNotNull(data)114 Assertions.assertEquals(200,response.statusCode)115 }116 }117 @Test118 fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() {119 val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680")120 .destination { response, url -> File.createTempFile("temp", ".tmp")121 }.progress { readBytes, totalBytes ->122 val progress = readBytes.toFloat() / totalBytes.toFloat()123 }.response ()124 val (data, error) = result125 Assertions.assertNull(error)126 Assertions.assertNotNull(data)127 Assertions.assertEquals(200,response.statusCode)128 }129 @Test130 fun whenMakeGetRequest_thenDeserializePostwithGson() {131 val latch = CountDownLatch(1)132 "https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject<Post> { _,_, result ->133 val post = result.component1()134 Assertions.assertEquals(1, post?.userId)135 latch.countDown()136 }137 latch.await()138 }139 @Test140 fun whenMakePOSTRequest_thenSerializePostwithGson() {141 val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet")142 val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts")143 .header("Content-Type" to "application/json")144 .body(Gson().toJson(post).toString())145 .response()146 Assertions.assertEquals(201,response.statusCode)147 }148 @Test149 fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() {150 val latch = CountDownLatch(1)151 "https://jsonplaceholder.typicode.com/posts?id=1"152 .httpGet().rx_object(Post.Deserializer()).subscribe{153 res, throwable ->154 val post = res.component1()155 Assertions.assertEquals(1, post?.get(0)?.userId)156 latch.countDown()157 }158 latch.await()159 }160 @Test161 fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() {162 runBlocking {163 val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse()164 result.fold({ data ->165 Assertions.assertEquals(200, response.statusCode)166 }, { error -> })167 }168 }169 @Test170 fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() {171 runBlocking {172 Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer())173 .fold({ data ->174 Assertions.assertEquals(1, data.get(0).userId)175 }, { error -> })176 }177 }178 @Test179 fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() {180 val latch = CountDownLatch(1)181 Fuel.request(PostRoutingAPI.posts("1",null))182 .responseObject(Post.Deserializer()) {183 request, response, result ->184 Assertions.assertEquals(1, result.component1()?.get(0)?.userId)185 latch.countDown()186 }187 latch.await()188 }189 @Test190 fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() {191 val latch = CountDownLatch(1)192 Fuel.request(PostRoutingAPI.comments("1",null))193 .responseString { request, response, result ->194 Assertions.assertEquals(200, response.statusCode)195 latch.countDown()196 }197 latch.await()198 }199}...
MojangKt.kt
Source:MojangKt.kt
1package dev.dewy.mojangkt2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.gson.jsonBody4import com.github.kittinunf.fuel.gson.responseObject5import com.github.kittinunf.fuel.httpDelete6import com.github.kittinunf.fuel.httpGet7import com.github.kittinunf.fuel.httpPost8import com.github.kittinunf.fuel.httpPut9import com.github.kittinunf.result.Result10import com.google.gson.Gson11import com.google.gson.JsonObject12import java.util.Base6413import java.util.UUID14import java.util.regex.Pattern15import kotlin.coroutines.resume16import kotlin.coroutines.resumeWithException17import kotlin.coroutines.suspendCoroutine18class MojangKt {19 private val gson = Gson()20 @Suppress("UNUSED")21 var token = ""22 set(value) {23 field = value24 if (value.isEmpty()) {25 FuelManager.instance.baseHeaders = emptyMap()26 return27 }28 FuelManager.instance.baseHeaders = mapOf(29 "Authorization" to "Bearer $value"30 )31 }32 suspend fun getPlayerFromName(name: String): PrimitivePlayer = suspendCoroutine { cont ->33 "https://api.mojang.com/users/profiles/minecraft/$name"34 .httpGet()35 .responseObject<PrimitivePlayer> { _, _, result ->36 when (result) {37 is Result.Failure -> {38 cont.resumeWithException(result.getException())39 }40 is Result.Success -> {41 cont.resume(result.value)42 }43 }44 }45 }46 suspend fun getPlayersFromNames(names: List<String>): List<PrimitivePlayer> = suspendCoroutine { cont ->47 "https://api.mojang.com/profiles/minecraft"48 .httpPost()49 .jsonBody(50 names, gson51 )52 .responseObject<List<PrimitivePlayer>> { _, _, result ->53 when (result) {54 is Result.Failure -> {55 cont.resumeWithException(result.getException())56 }57 is Result.Success -> {58 cont.resume(result.value)59 }60 }61 }62 }63 suspend fun getProfileFromUuid(uuid: String): Profile = suspendCoroutine { cont ->64 "https://sessionserver.mojang.com/session/minecraft/profile/$uuid"65 .httpGet()66 .responseString {_, _, result ->67 when (result) {68 is Result.Failure -> {69 cont.resumeWithException(result.getException())70 }71 is Result.Success -> {72 val obj = gson.fromJson(result.value, JsonObject::class.java)73 val encodedProperties = obj["properties"].asJsonArray[0].asJsonObject["value"].asString74 val id = obj["id"].asString75 val name = obj["name"].asString76 val legacy = obj.has("legacy")77 var skinUrl = ""78 var skinType = getSkinType(id)79 var capeUrl = ""80 if (encodedProperties != null) {81 val texturesObj = gson.fromJson(String(Base64.getDecoder()82 .decode(encodedProperties)), JsonObject::class.java)83 .getAsJsonObject("textures")84 val skinObj = texturesObj.getAsJsonObject("SKIN")85 val capeObj = texturesObj.getAsJsonObject("CAPE")86 if (skinObj != null) {87 skinUrl = skinObj["url"].asString88 skinType = if (skinObj.has("metadata")) SkinType.SLIM else SkinType.DEFAULT89 }90 if (capeObj != null) {91 capeUrl = capeObj["url"].asString92 }93 }94 cont.resume(Profile(PrimitivePlayer(id, name, legacy), Skin(skinUrl, skinType), capeUrl))95 }96 }97 }98 }99 suspend fun getNameHistory(uuid: String): NameHistory = suspendCoroutine { cont ->100 "https://api.mojang.com/user/profiles/$uuid/names"101 .httpGet()102 .responseObject<List<NameHistoryNode>> { _, _, result ->103 when (result) {104 is Result.Failure -> {105 cont.resumeWithException(result.getException())106 }107 is Result.Success -> {108 cont.resume(NameHistory(result.value))109 }110 }111 }112 }113 suspend fun changeName(name: String) = suspendCoroutine<Unit> { cont ->114 "https://api.minecraftservices.com/minecraft/profile/name/$name"115 .httpPut()116 .response { _, response, result ->117 when (result) {118 is Result.Failure -> {119 when (response.statusCode) {120 400 -> cont.resumeWithException(InvalidNameException("Name must follow Mojang's name rules."))121 401 -> cont.resumeWithException(UnauthorizedAccessException("Token expired or incorrect."))122 403 -> cont.resumeWithException(UnavailableNameException("Name either taken or is in some other way unavailable."))123 500 -> cont.resumeWithException(TimedOutException("Timed out."))124 }125 }126 is Result.Success -> {127 cont.resume(Unit)128 }129 }130 }131 }132 suspend fun resetSkin(uuid: String) = suspendCoroutine<Unit> { cont ->133 "https://api.mojang.com/user/profile/$uuid/skin"134 .httpDelete()135 .responseString { _, _, result ->136 when (result) {137 is Result.Failure -> {138 cont.resumeWithException(result.getException())139 }140 is Result.Success -> {141 val errorObj = gson.fromJson(result.value, JsonObject::class.java)142 if (errorObj != null)143 cont.resumeWithException(MojangApiException("${errorObj["error"].asString}: ${errorObj["errorMessage"].asString}"))144 else145 cont.resume(Unit)146 }147 }148 }149 }150 suspend fun getBlockedServers(): List<String> = suspendCoroutine { cont ->151 "https://sessionserver.mojang.com/blockedservers"152 .httpGet()153 .responseString { _, _, result ->154 when (result) {155 is Result.Failure -> {156 cont.resumeWithException(result.getException())157 }158 is Result.Success -> {159 cont.resume(result.value.split("\n"))160 }161 }162 }163 }164 @Suppress("NAME_SHADOWING")165 private fun getSkinType(uuid: String): SkinType {166 val uuid = UUID.fromString(Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})")167 .matcher(uuid.replace("-", "")).replaceAll("$1-$2-$3-$4-$5"))168 return if ((uuid.hashCode() and 1) != 0)169 SkinType.SLIM170 else171 SkinType.DEFAULT172 }173}...
RestAPI.kt
Source:RestAPI.kt
1package org.intellij.plugin.zeppelin.api.remote.rest2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Response4import com.github.kittinunf.fuel.httpDelete5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.httpPut8import com.github.kittinunf.fuel.moshi.responseObject9import com.github.kittinunf.result.Result10import org.intellij.plugin.zeppelin.utils.JsonParser11open class RestAPI(host: String, port: Int, https: Boolean = false) {12 private val protocol: String = if (https) "https" else "http"13 private val apiUrl: String = "$protocol://$host:$port/api"14 fun performGetRequest(uri: String,15 credentials: String?): RestResponseMessage {16 val headers = credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap()17 val (_, _, result) = "$apiUrl$uri".httpGet()18 .header(headers)19 .timeout(10000)20 .responseObject<RestResponseMessage>()21 return getResponse(result)22 }23 fun performPostData(uri: String, data: Map<String, Any>, credentials: String?): RestResponseMessage {24 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/json").plus(25 credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap())26 val (_, _, result) = "$apiUrl$uri".httpPost()27 .header(headers)28 .body(JsonParser.toJson(data))29 .timeout(10000)30 .responseObject<RestResponseMessage>()31 return getResponse(result)32 }33 fun performDeleteData(uri: String, credentials: String?): RestResponseMessage {34 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/json").plus(35 credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap())36 val (_, _, result) = "$apiUrl$uri".httpDelete()37 .header(headers)38 .timeout(10000)39 .responseObject<RestResponseMessage>()40 return getResponse(result)41 }42 fun performPostForm(uri: String, params: Map<String, String>): Pair<Response, RestResponseMessage> {43 val paramString = "?" + params.map { it.key + "=" + it.value }.joinToString("&")44 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/x-www-form-urlencoded")45 val (_, response, result) = "$apiUrl$uri$paramString".httpPost()46 .header(headers)47 .timeout(10000)48 .responseObject<RestResponseMessage>()49 return Pair(response, getResponse(result))50 }51 fun performPutData(uri: String, data: Map<String, Any>,52 credentials: String?): RestResponseMessage {53 val headers = mapOf("Charset" to "UTF-8", "Content-Type" to "application/json").plus(54 credentials?.let { mapOf("Cookie" to credentials) } ?: emptyMap())55 val (_, _, result) = "$apiUrl$uri".httpPut()56 .header(headers)57 .body(JsonParser.toJson(data))58 .timeout(10000)59 .responseObject<RestResponseMessage>()60 return getResponse(result)61 }62 private fun getResponse(63 result: Result<RestResponseMessage, FuelError>): RestResponseMessage {64 val (obj, errors) = result65 if (errors != null) {66 throw errors67 }68 return obj!!69 }70}71data class RestResponseMessage(val status: String, val message: String, val body: Any = Any())...
TmdbUtilImpl.kt
Source:TmdbUtilImpl.kt
1package ash.kotlin.graphql.data2import ash.kotlin.graphql.AppConfig3import ash.kotlin.graphql.TmdbGqlException4import ash.kotlin.graphql.types.genre.GenreType5import ash.kotlin.graphql.types.keyword.KeywordType6import ash.kotlin.graphql.types.movie.MovieType7import ash.kotlin.graphql.types.multisearch.PersonType8import ash.kotlin.graphql.types.multisearch.TvShowType9import ash.kotlin.graphql.types.tvseason.TvSeasonType10import com.github.kittinunf.fuel.core.FuelManager11import com.github.kittinunf.fuel.core.ResponseDeserializable12import com.github.kittinunf.fuel.gson.responseObject13import com.github.kittinunf.fuel.httpGet14import com.github.kittinunf.result.Result15import com.google.gson.Gson16import com.google.gson.JsonParser17import org.jvnet.hk2.annotations.Service18import javax.inject.Inject19class TmdbUtilImpl @Inject constructor(config: AppConfig) : TmdbUtil20{21 init22 {23 FuelManager.instance.basePath = config.baseUrl24 }25 override fun getGenreList(): List<GenreType>26 {27 return sendListRequest("/genre/movie/list")28 }29 override fun getMovieKeywords(movieId: Int): List<KeywordType>30 {31 return sendListRequest("/movie/$movieId/keywords")32 }33 override fun getTvSeason(tvShowId: Int, seasonNumber: Int): TvSeasonType34 {35 return sendRequest("/tv/$tvShowId/season/$seasonNumber") ?: TvSeasonType()36 }37 override fun searchMoviesWithQuery(query: String): List<MovieType>38 {39 return sendListRequest("/search/movie", listOf(query to "query"))40 }41 override fun searchMoviesWithMultipleParameters(params: List<Pair<String, Any?>>): List<MovieType>42 {43 return sendListRequest("/search/movie", params)44 }45 override fun searchMulti(params: List<Pair<String, Any?>>): List<Any>46 {47 var data = emptyList<Any>()48 "/search/multi".httpGet(params).responseObject(MultiDeserializer()) { _, _, result ->49 when (result)50 {51 is Result.Failure -> throw TmdbGqlException(result.error)52 is Result.Success -> data = result.get()53 }54 }55 return data56 }57 private class MultiDeserializer : ResponseDeserializable<List<Any>>58 {59 override fun deserialize(content: String): List<Any>?60 {61 val gson = Gson()62 val objectList = mutableListOf<Any>()63 val responseJson = JsonParser().parse(content).asJsonObject["results"].asJsonArray64 responseJson.forEach {65 val jsonObject = it.asJsonObject66 val mediaType = jsonObject["media_type"].asString67 when (mediaType)68 {69 "movie" -> objectList.add(gson.fromJson(it, MovieType::class.java))70 "tv" -> objectList.add(gson.fromJson(it, TvShowType::class.java))71 "person" -> objectList.add(gson.fromJson(it, PersonType::class.java))72 }73 }74 return objectList75 }76 }77 private inline fun <reified T : Any> sendRequest(url: String): T?78 {79 var data: T? = null80 url.httpGet().responseObject<T> { _, _, result ->81 when (result)82 {83 is Result.Failure -> throw TmdbGqlException(result.error)84 is Result.Success -> data = result.get()85 }86 }87 return data88 }89 private fun <T : Any> sendListRequest(url: String, params: List<Pair<String, Any?>> = emptyList()): List<T>90 {91 var data = emptyList<T>()92 url.httpGet(params).responseObject<List<T>> { _, _, result ->93 when (result)94 {95 is Result.Failure -> throw TmdbGqlException(result.error)96 is Result.Success -> data = result.get()97 }98 }99 return data100 }101}...
QrScanResultDialog.kt
Source:QrScanResultDialog.kt
1package com.example.easyin2import android.app.Dialog3import android.content.Context4import kotlinx.android.synthetic.main.qr_result_dialog.*5import com.github.kittinunf.fuel.Fuel6import com.github.kittinunf.fuel.core.FuelError7import com.github.kittinunf.fuel.core.Request8import com.github.kittinunf.fuel.core.Response9import com.github.kittinunf.fuel.core.awaitResult10import com.github.kittinunf.fuel.core.extensions.jsonBody11import com.github.kittinunf.fuel.httpGet12import com.github.kittinunf.fuel.httpPost13import com.github.kittinunf.fuel.json.jsonDeserializer14import com.github.kittinunf.fuel.json.responseJson15import com.github.kittinunf.result.Result;16import org.json.JSONObject17import kotlin.reflect.typeOf18class QrScanResultDialog(var context : Context) {19 private lateinit var dialog: Dialog20 private var qrResultUrl : String = ""21 var email : String = ""22 init {23 initDialog()24 }25 private fun initDialog() {26 dialog = Dialog(context)27 dialog.setContentView(R.layout.qr_result_dialog)28 dialog.setCancelable(false)29 Onclicks()30 }31 fun show(qrResult: String) {32 qrResultUrl = qrResult33 dialog.scannedText.text = qrResultUrl34 email = qrResultUrl35 dialog.show()36 }37 private fun Onclicks() {38 dialog.postResult.setOnClickListener {39 postResult(qrResultUrl)40 }41 dialog.cancelDialog.setOnClickListener {42 dialog.dismiss()43 }44 }45// Adding an identity to the system46private fun postResult(Url: String) {47 val dataPOST = JSONObject()48 dataPOST.put("email", email)49 println(dataPOST)50 "http://oneeasyin.com:8080/identity/postidentity"51 .httpPost()52 .header("Content-Type" to "application/json")53 .body(dataPOST.toString()).responseJson {54 request, response, result ->55 when (result) {56 is Result.Failure -> {57 val ex = result.getException()58 println(ex)59 }60 is Result.Success -> {61 val data = result.get().obj()62 println(data)63 }64 }65 }66 }67 }...
RemoteRepo.kt
Source:RemoteRepo.kt
1package com.funglejunk.stockecho.repo2import arrow.core.Either3import arrow.core.extensions.either.monad.flatten4import arrow.fx.IO5import com.funglejunk.stockecho.data.History6import com.github.kittinunf.fuel.core.FuelError7import com.github.kittinunf.fuel.core.Parameters8import com.github.kittinunf.fuel.coroutines.awaitStringResult9import com.github.kittinunf.fuel.httpGet10import kotlinx.serialization.UnsafeSerializationApi11import kotlinx.serialization.json.Json12import kotlinx.serialization.serializer13import timber.log.Timber14import java.time.LocalDate15@UnsafeSerializationApi16object RemoteRepo {17 private const val BASE_URL = "https://api.boerse-frankfurt.de/data"18 private const val PRICE_HISTORY_EP = "/price_history"19 private const val ISIN_PARAM_ID = "isin"20 private const val MIN_DATE_ID = "minDate"21 private const val MAX_DATE_ID = "maxDate"22 private val OFFSET_PARAM = "offset" to 023 private val LIMIT_PARAM = "limit" to 50524 private val MIC_PARAM = "mic" to "XETR"25 fun getHistory(26 isin: String,27 minDate: LocalDate,28 maxDate: LocalDate29 ): IO<Either<Throwable, History>> = IO {30 req(31 BASE_URL + PRICE_HISTORY_EP,32 listOf(33 OFFSET_PARAM,34 LIMIT_PARAM,35 MIC_PARAM,36 ISIN_PARAM_ID to isin,37 MIN_DATE_ID to minDate,38 MAX_DATE_ID to maxDate39 )40 )41 }42 private suspend inline fun <reified T : Any> req(43 url: String,44 params: Parameters? = null45 ): Either<Throwable, T> = Either.catch {46 val response = url.httpGet(params).awaitStringResult().catchable()47 response.deserialize<T>()48 }.flatten()49 private suspend inline fun <reified T : Any> String.deserialize(): Either<Throwable, T> =50 Either.catch {51 Json.decodeFromString(deserializer = T::class.serializer(), string = this)52 }.also {53 if (it.isLeft()) {54 Timber.e("Error deserializing to ${T::class.java}: $this")55 }56 }57 private fun com.github.kittinunf.result.Result<String, FuelError>.catchable(): String =58 fold(59 { it },60 {61 Timber.e("Error fetching url: $it")62 throw it63 }64 )65}...
ArticleDataProvider.kt
Source:ArticleDataProvider.kt
1package com.example.mywiki.providers2import com.example.mywiki.models.Urls3import com.example.mywiki.models.WikiResult4import com.github.kittinunf.fuel.core.FuelManager5import com.github.kittinunf.fuel.core.ResponseDeserializable6import com.github.kittinunf.fuel.core.ResponseHandler7import com.github.kittinunf.fuel.core.isSuccessful8import com.github.kittinunf.fuel.httpGet9import com.google.gson.Gson10import java.io.Reader11class ArticleDataProvider12{13 init14 {15 FuelManager.instance.baseHeaders = mapOf("User-Agent" to "Tester Wikipedia")16 }17 class WikipediaDataDeserializer : ResponseDeserializable<WikiResult>18 {19 override fun deserialize(reader: Reader): WikiResult? =20 Gson().fromJson(reader, WikiResult::class.java)21 }22 fun search(term: String, skip: Int, take: Int, responseHandler: (result: WikiResult) -> Unit?)23 {24 Urls.getSearchUrl(term, skip, take).httpGet()25 .responseObject(WikipediaDataDeserializer()) { _, _, result ->26 val (data, _) = result27 responseHandler.invoke(data as WikiResult)28 }29 }30 fun getRandom(take: Int, responseHandler: (result: WikiResult) -> Unit?)31 {32 Urls.getRandomUrl(take).httpGet()33 .responseObject(WikipediaDataDeserializer()) { _, response, result ->34// if(response.statusCode != 200)35 if (!response.isSuccessful)36 throw Exception("Unable to get articles")37 val (data, error) = result38 responseHandler.invoke(data as WikiResult)39 }40 }41}...
FuelHttpClient.kt
Source:FuelHttpClient.kt
1package com.mvelusce.recipebook.http2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Request4import com.github.kittinunf.fuel.core.Response5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.result.Result7class FuelHttpClient : HttpClient<String> {8 override fun get(url: String, parameters: List<Pair<String, Any?>>?):9 Triple<Request, Response, Result<String, FuelError>> =10 url.httpGet(parameters).responseString()11}...
String.httpGet
Using AI Code Generation
1import com.github.kittinunf.fuel.Fuel2val (request, response, result) = url.httpGet().responseString()3println(request)4println(response)5println(result.get())6Server: nginx/1.10.3 (Ubuntu)7Content-Type: application/json; charset=utf-88X-XSS-Protection: 1; mode=block9Report-To: {"endpoints":[{"url":"https:\/\
String.httpGet
Using AI Code Generation
1val (request, response, result) = url.httpGet().responseString()2result.fold({ data ->3}, { error ->4})5val (request, response, result) = url.httpPost().responseString()6result.fold({ data ->7}, { error ->8})9val (request, response, result) = url.httpPut().responseString()10result.fold({ data ->11}, { error ->12})13val (request, response, result) = url.httpDelete().responseString()14result.fold({ data ->15}, { error ->16})17val (request, response, result) = url.httpPatch().responseString()18result.fold({ data ->19}, { error ->20})21val (request, response, result) = url.httpHead().responseString()22result.fold({ data ->23}, { error ->24})25val (request, response, result) = url.httpOptions().responseString()26result.fold({ data ->27}, { error ->28})
String.httpGet
Using AI Code Generation
1fun String.httpGet(): String {2 Fuel.get(this).responseString { request, response, result ->3 result.fold({ data ->4 }, { err ->5 })6 }7}8fun String.httpPost(): String {9 Fuel.post(this).responseString { request, response, result ->10 result.fold({ data ->11 }, { err ->12 })13 }14}15fun String.httpPut(): String {16 Fuel.put(this).responseString { request, response, result ->17 result.fold({ data ->18 }, { err ->19 })20 }21}22fun String.httpDelete(): String {23 Fuel.delete(this).responseString { request, response, result ->24 result.fold({ data ->25 }, { err ->26 })27 }28}29fun String.httpPatch(): String {30 Fuel.patch(this).responseString { request, response, result ->31 result.fold({ data ->32 }, { err ->33 })34 }35}
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!!