How to use post method of com.github.kittinunf.fuel.core.FuelManager class

Best Fuel code snippet using com.github.kittinunf.fuel.core.FuelManager.post

FuelHttpLiveTest.kt

Source:FuelHttpLiveTest.kt Github

copy

Full Screen

...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// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library161// @Test162// fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() = runBlocking {163// val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse()164//165// result.fold({ data ->166// Assertions.assertEquals(200, response.statusCode)167//168// }, { error -> })169// }170// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library171// @Test172// fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() = runBlocking {173// Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer())174// .fold({ data ->175// Assertions.assertEquals(1, data.get(0).userId)176// }, { error -> })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()...

Full Screen

Full Screen

FuelHttpUnitTest.kt

Source:FuelHttpUnitTest.kt Github

copy

Full Screen

...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()...

Full Screen

Full Screen

HttpUtils.kt

Source:HttpUtils.kt Github

copy

Full Screen

1package vkm.vkm.utils2import com.github.kittinunf.fuel.android.core.Json3import com.github.kittinunf.fuel.android.extension.responseJson4import com.github.kittinunf.fuel.core.FuelManager5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.result.Result8import kotlinx.coroutines.Dispatchers9import kotlinx.coroutines.GlobalScope10import kotlinx.coroutines.Job11import kotlinx.coroutines.launch12import org.jsoup.Jsoup13import vkm.vkm.State14import vkm.vkm.utils.db.ProxyDao15import java.net.InetSocketAddress16import java.util.concurrent.ConcurrentHashMap17import kotlin.coroutines.resume18import kotlin.coroutines.resumeWithException19import kotlin.coroutines.suspendCoroutine20typealias JProxy = java.net.Proxy21object HttpUtils {22 private val proxyBlacklist = ConcurrentHashMap<Proxy, Long>()23 private val untrustedProxyList = mutableListOf<Proxy>()24 var currentProxy: Proxy? = null25 private fun setProxy(proxy: Proxy?) {26 proxy?.let {27 "Using proxy: $proxy".log()28 currentProxy = proxy29 currentProxy?.type = "current"30 }31 FuelManager.instance = FuelManager()32 FuelManager.instance.proxy = proxy?.let { JProxy(java.net.Proxy.Type.HTTP, InetSocketAddress(it.host, it.port)) }33 FuelManager.instance.timeoutInMillisecond = 500034 FuelManager.instance.timeoutReadInMillisecond = 500035 }36 private fun setProxies(list: List<Proxy>) {37 proxyBlacklist.clear()38 untrustedProxyList.clear()39 list.forEach {40 when (it.type) {41 "current" -> currentProxy = it42 "untrusted" -> untrustedProxyList.add(it)43 else -> proxyBlacklist[it] = it.added44 }45 }46 }47 private fun getBlackList(): List<Proxy> {48 return proxyBlacklist.map {49 it.key.added = it.value50 it.key51 }52 }53 fun storeProxies(dao: ProxyDao): Job {54 // slow but simple55 return GlobalScope.launch(Dispatchers.IO) {56 val blackList = HttpUtils.getBlackList().filter { it.added > System.currentTimeMillis() - 1000 * 60 * 60 * 24 }57 dao.deleteAll()58 dao.insertAll(blackList)59 dao.insertAll(untrustedProxyList)60 currentProxy?.let {61 it.type = "current"62 dao.insert(it)63 }64 }65 }66 fun loadProxies(dao: ProxyDao): Job {67 return GlobalScope.launch(Dispatchers.IO) {68 HttpUtils.setProxies(dao.getAll())69 }70 }71 suspend fun call4Json(method: HttpMethod, url: String, withProxy: Boolean = false): Json? {72 for (retries in 0..10) {73 try {74 return callHttp(method, url, withProxy)75 } catch (e: ProxyNotAvailableException) {76 if (currentProxy == null) {77 return null78 }79 "Retrying with another proxy".log()80 } catch (e: Exception) {81 "Error connecting".logE(e)82 break83 }84 }85 return null86 }87 private suspend fun callHttp(method: HttpMethod = HttpMethod.GET, url: String, withProxy: Boolean = false): Json {88 setProxy(if (State.useProxy && withProxy) getProxy() else null)89 "Calling: $method $url".log()90 val caller = when (method) {91 HttpMethod.GET -> url.httpGet()92 HttpMethod.POST -> url.httpPost()93 }94 return suspendCoroutine { continuation ->95 caller.responseJson { _, resp, result ->96 try {97 if (result is Result.Success && resp.headers["Content-Type"]?.firstOrNull()?.contains("application/json") == true) {98 "Received result ${result.component1()?.content}".log()99 continuation.resume(result.component1()!!)100 return@responseJson101 } else {102 val currProxy = currentProxy103 if (currProxy != null) {104 "Blacklisting $currProxy".log()105 currProxy.type = "blacklisted"106 proxyBlacklist[currProxy] = System.currentTimeMillis()107 }108 result.component2().toString().logE()109 throw ProxyNotAvailableException()110 }111 } catch (e: Exception) {112 continuation.resumeWithException(e)113 }114 }115 }116 }117 private suspend fun getProxy(): Proxy? {118 val currProxy = currentProxy119 if (currProxy != null && proxyBlacklist[currProxy] == null) {120 return currProxy121 }122 var fetched = false123 while (true) {124 if (untrustedProxyList.isEmpty()) {125 if (fetched) {126 return null127 } // we have already fetched during this iteration, next fetch will bring the same results128 untrustedProxyList.addAll(fetchProxyList())129 fetched = true130 }131 val proxy = untrustedProxyList[0]132 val time = proxyBlacklist[proxy] ?: return proxy133 if (System.currentTimeMillis() - time > 1000 * 60 * 60 * 24) {134 proxyBlacklist.remove(proxy)135 return proxy136 }137 // it is still blacklisted, removing from a list138 untrustedProxyList.removeAt(0)139 }140 }141 private suspend fun fetchProxyList(): List<Proxy> {142 "Fetching proxy list".log()143 return suspendCoroutine { continuation ->144 try {145 Jsoup.connect("https://www.proxy" + "nova.com/proxy-server-list/country-ru/").get().run {146 "Proxy list fetched".log()147 val result = getElementById("tbl_p" + "roxy_list").select("tbody tr").map { row ->148 if (!row.hasAttr("data-proxy-id")) {149 return@map Proxy("", 0)150 }151 val columns = row.select("td")152 val ip = columns[0].select("abbr").html().replace(Regex(".*?(\\d+\\.\\d+\\.\\d+\\.\\d+).*"), "$1")153 val port = columns[1].select("a").text()154 val speed = columns[3].select("small").text().split(" ")[0]155 val type = columns[6].select("span").text()156 if (port.isBlank() || speed.isBlank()) {157 return@map Proxy("", 0)158 }159 Proxy(host = ip, port = port.toInt(), type = "untrusted", speed = speed.toInt())160 }.filter { it.port != 0 && it.host.isNotEmpty() }161 continuation.resume(result)162 }163 } catch (e: Exception) {164 continuation.resumeWithException(e)165 }166 }167 }168}169enum class HttpMethod {170 GET,171 POST172 ;173}...

Full Screen

Full Screen

NetworkManager.kt

Source:NetworkManager.kt Github

copy

Full Screen

...44 }45 inline fun <reified T : Any> put(url: String, body: Any): LiveData<NetResp<T>> {46 return doRequest(url.httpPut().jsonBody(body))47 }48 inline fun <reified T : Any> post(url: String, body: Any): LiveData<NetResp<T>> {49 return doRequest(url.httpPost().jsonBody(body))50 }51 inline fun <reified T : Any> delete(url: String, body: Any): LiveData<NetResp<T>> {52 return doRequest(url.httpDelete().jsonBody(body))53 }54 inline fun <reified T : Any> doRequest(request: Request): LiveData<NetResp<T>> {55 var result: NetResp<T> by Delegates.notNull()56 var resp = MutableLiveData<NetResp<T>>()57 GlobalScope.launch(Dispatchers.Main) {58 request.executionOptions.responseValidator = {59 true60 }61 withContext(Dispatchers.IO) {62 var respObj = request.responseObject<NetResp<T>>()63 if (respObj.third.component2() == null) {64 val respData = respObj.third.get()65 respData.httpCode = respObj.second.statusCode66 result = respData67 } else {68 respObj.third.component2()!!.printStackTrace()69 result = NetResp("未知错误", -1, null, -1)70 }71 }72 resp.value = result73 }74 return resp75 }76 inline fun <reified T : Any> postSync(url: String, body: Any): NetResp<T> {77 return doRequestSync(url.httpPost().jsonBody(body))78 }79 inline fun <reified T : Any> doRequestSync(request: Request): NetResp<T> {80 var result: NetResp<T> by Delegates.notNull()81 GlobalScope.launch(Dispatchers.Main) {82 request.executionOptions.responseValidator = {83 true84 }85 val respObj = request.responseObject<NetResp<T>>()86 if (respObj.third.component2() == null) {87 val respData = respObj.third.get()88 respData.httpCode = respObj.second.statusCode89 result = respData90 } else {...

Full Screen

Full Screen

FuelWebService.kt

Source:FuelWebService.kt Github

copy

Full Screen

...39 inline fun <reified T: Any> head(url: String,40 crossinline success: (Request, Response, T) -> Unit,41 noinline failure: ((Request, Response, Exception) -> Unit)? = null42 ): Request = request<T>(Fuel.head(url), success, failure)43 inline fun <reified T: Any> post(url: String,44 crossinline success: (Request, Response, T) -> Unit,45 noinline failure: ((Request, Response, Exception) -> Unit)? = null46 ): Request = request<T>(Fuel.post(url), success, failure)47 inline fun <reified T: Any> put(url: String,48 crossinline success: (Request, Response, T) -> Unit,49 noinline failure: ((Request, Response, Exception) -> Unit)? = null50 ): Request = request<T>(Fuel.put(url), success, failure)51 inline fun <reified T: Any> delete(url: String,52 crossinline success: (Request, Response, T) -> Unit,53 noinline failure: ((Request, Response, Exception) -> Unit)? = null54 ): Request = request<T>(Fuel.delete(url), success, failure)55 @Deprecated("@hide")56 inline fun <reified T: Any> request(request: Request,57 crossinline success: (Request, Response, T) -> Unit,58 noinline failure: ((Request, Response, Exception) -> Unit)? = null59 ): Request = request.responseObject(Deserializer(gson, T::class)) { _, response, result: Result<T, FuelError> ->60 result.fold({ data ->...

Full Screen

Full Screen

UserService.kt

Source:UserService.kt Github

copy

Full Screen

...43 }4445 suspend fun createUser() = withContext(Dispatchers.IO) {46 Fuel47 .post("/user")48 .body("{\"action\": \"CREATE\"}")49 .set("Content-Type", "application/json")50 .to<User>()51 }5253 suspend fun like(from: ID, to: ID) = Fuel54 .post("/user")55 .body("{\"action\": \"LIKE\", \"from\": \"$from\", \"to\":\"$to\"}")56 .set("Content-Type", "application/json")57 .raw()585960 suspend fun getChats(room_id: String) =61 Fuel.get("/chat/$room_id")62 .awaitObjectResult<Array<Chat>>(object : ResponseDeserializable<Array<Chat>> {63 override fun deserialize(content: String) = Gson().fromJson(content, Array<Chat>::class.java)})6465 suspend fun chat(room_id: String, from: ID, message: String) =66 Fuel.post("/chat/$room_id")67 .body("{\"message\":\"$message\", \"from\": \"$from\"}")68 .set("Content-Type", "application/json")69 .raw()7071} ...

Full Screen

Full Screen

FuelHttpConnectorImpl.kt

Source:FuelHttpConnectorImpl.kt Github

copy

Full Screen

...12class FuelHttpConnectorImpl: HttpConnector {13 companion object {14 val hashService= HashServiceImpl()15 }16 override fun post(url: String, headers: Map<String, String>, payload: String?): String {17 val request = FuelManager.instance.request(Method.POST, url)18 headers.forEach { k, v -> request.header(k to v) }19 payload?.let {20 request.body(payload, Charset.defaultCharset())21 }22 request.timeout(10000)23 request.timeoutRead(10000)24 val (_, _, result) = request.responseString()25 when (result) {26 is Result.Success -> {27 return result.getAs<String>()!!28 }29 is Result.Failure -> {30 throw IllegalStateException("Timeout calling $url.")...

Full Screen

Full Screen

LogEvent.kt

Source:LogEvent.kt Github

copy

Full Screen

1// Copyright 2018 Sourcerer Inc. All Rights Reserved.2// Author: Alexander Surkov (alex@sourcerer.io)3package sourcererio.vacuumanalytics4import com.github.kittinunf.fuel.core.FuelError5import com.github.kittinunf.fuel.core.FuelManager6import com.github.kittinunf.fuel.core.Method7import com.github.kittinunf.fuel.core.Request8import com.github.kittinunf.fuel.core.Response9import java.net.HttpCookie10import java.util.Date11/**12 * Elastic LogStash logging.13 */14class LogEvent {15 // Unique identifier of the session.16 private var session: String = ""17 private val fuelManager = FuelManager()18 /**19 * Creates a LogEvent instance.20 *21 * @param path [in] path to send logs to,22 * @param res [in] HTTP response of successful user authorization,23 * @param sid [in] session id of the HTTP response.24 */25 constructor(path: String,26 res: Response, sid: String) {27 res.headers["Set-Cookie"]?.28 flatMap { HttpCookie.parse(it) }?.29 find { it.name == sid }?.30 let { session = it.value }31 fuelManager.basePath = path32 }33 /**34 * Logs error.35 */36 fun error(message: String) {37 event("error", message)38 }39 /**40 * Logs event.41 */42 fun event(type: String, message: String) {43 event(type, listOf("message" to message))44 }45 /**46 * Logs event.47 */48 fun event(type: String, fields: List<Pair<String, Any?>>) {49 var params = mutableListOf<Pair<String, Any?>>(50 "session" to session,51 "type" to type,52 "timestamp" to Date().getTime()53 )54 fuelManager.55 request(56 Method.POST,57 "",58 params.plus(fields)59 )60 .response { _, _, result ->61 val (_, err) = result62 if (err != null) {63 throw Exception("FAILED to send logs: $err")64 }65 }66 }67}...

Full Screen

Full Screen

post

Using AI Code Generation

copy

Full Screen

1class MainActivity : AppCompatActivity() {2override fun onCreate(savedInstanceState: Bundle?) {3 super.onCreate(savedInstanceState)4 setContentView(R.layout.activity_main)5 val manager = FuelManager()6 val request = Request()7}8}

Full Screen

Full Screen

post

Using AI Code Generation

copy

Full Screen

1val manager = FuelManager()2manager.baseHeaders = mapOf("Content-Type" to "application/json")3manager.baseParams = listOf("key" to "value")4manager.baseOptions = listOf(TimeoutRead(3000))5manager.baseBody = "{\"foo\":\"bar\"}".toByteArray()6manager.request("/post").responseString { _, _, result ->7result.fold({ d ->8println(d)9}, { err ->10println(err)11})12}13val manager = FuelManager()14manager.baseHeaders = mapOf("Content-Type" to "application/json")15manager.baseParams = listOf("key" to "value")16manager.baseOptions = listOf(TimeoutRead(3000))17manager.request("/get").responseString { _, _, result ->18result.fold({ d ->19println(d)20}, { err ->21println(err)22})23}24val manager = FuelManager()25manager.baseHeaders = mapOf("Content-Type" to "application/json")26manager.baseParams = listOf("key" to "value")27manager.baseOptions = listOf(TimeoutRead(3000))28manager.baseBody = "{\"foo\":\"bar\"}".toByteArray()29manager.request("/put").responseString { _, _, result ->30result.fold({ d ->31println(d)32}, { err ->33println(err)34})35}36val manager = FuelManager()37manager.baseHeaders = mapOf("Content-Type" to "application/json")38manager.baseParams = listOf("key" to "value")39manager.baseOptions = listOf(TimeoutRead(3000))40manager.baseBody = "{\"foo\":\"bar\"}".toByteArray()41manager.request("/delete").responseString { _, _, result ->42result.fold({ d ->43println(d)44}, { err ->45println(err)46})47}

Full Screen

Full Screen

post

Using AI Code Generation

copy

Full Screen

1val parameters = listOf("foo" to "bar")2Fuel.post(url, parameters).responseString { request, response, result ->3println(request)4println(response)5println(result)6}7val parameters = listOf("foo" to "bar")8Fuel.put(url, parameters).responseString { request, response, result ->9println(request)10println(response)11println(result)12}13Fuel.delete(url).responseString { request, response, result ->14println(request)15println(response)16println(result)17}18val parameters = listOf("foo" to "bar")19Fuel.patch(url, parameters).responseString { request, response, result ->20println(request)21println(response)22println(result)23}24Fuel.head(url).responseString { request, response, result ->25println(request)26println(response)27println(result)28}29Fuel.options(url).responseString { request, response, result ->30println(request)31println(response)32println(result)33}34Fuel.trace(url).responseString { request, response, result ->35println(request)36println(response)37println(result)38}39Fuel.connect(url).responseString { request, response, result ->40println(request)41println(response)42println(result)43}

Full Screen

Full Screen

post

Using AI Code Generation

copy

Full Screen

1println(request)2println(response)3println(result)4println(request)5println(response)6println(result)7println(request)8println(response)9println(result)10println(request)11println(response)12println(result)13println(request)14println(response)15println(result)16println(request)17println(response)18println(result)19println(request)20println(response)21println(result)22println(request)23println(response)24println(result)25println(request)26println(response)27println(result)28val (request, response, result) = FuelManager.instance

Full Screen

Full Screen

post

Using AI Code Generation

copy

Full Screen

1fun postRequest(url: String, params: List<Pair<String, String>>): String {2val (request, response, result) = Fuel.post(url, params).responseString()3println(request)4println(response)5return result.get()6}7fun getRequest(url: String): String {8val (request, response, result) = Fuel.get(url).responseString()9println(request)10println(response)11return result.get()12}13fun deleteRequest(url: String): String {14val (request, response, result) = Fuel.delete(url).responseString()15println(request)16println(response)17return result.get()18}19fun putRequest(url: String, params: List<Pair<String, String>>): String {20val (request, response, result) = Fuel.put(url, params).responseString()21println(request)22println(response)23return result.get()24}25fun request(url: String, method: Method): String {26val (request, response, result) = Fuel.request(method, url).responseString()27println(request)28println(response)29return result.get()30}31fun download(url: String, file: File): String {32val (request, response, result) = Fuel.download(url).fileDestination { _, _ -> file }.responseString()33println(request)34println(response)35return result.get()36}37fun upload(url: String, file: File): String {38val (request, response, result) = Fuel.upload(url).source { _, _ -> file.inputStream() }.responseString()39println(request)40println(response)41return result.get()42}43fun download(url: String, file: File): String {44val (request, response, result) = Fuel.download(url).fileDestination { _, _ -> file }.responseString()45println(request)46println(response)

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful