How to use String.httpPut method of com.github.kittinunf.fuel.Fuel class

Best Fuel code snippet using com.github.kittinunf.fuel.Fuel.String.httpPut

TasksApi.kt

Source:TasksApi.kt Github

copy

Full Screen

1package org.hse.ataskmobileclient.apis2import android.util.Log3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult5import com.github.kittinunf.fuel.gson.jsonBody6import com.github.kittinunf.fuel.httpDelete7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.fuel.httpPost9import com.github.kittinunf.fuel.httpPut10import com.github.kittinunf.result.Result11import com.google.gson.Gson12import com.google.gson.reflect.TypeToken13import org.hse.ataskmobileclient.dto.GoogleImageDto14import org.hse.ataskmobileclient.dto.TaskDto15import org.hse.ataskmobileclient.models.Urls16import java.text.SimpleDateFormat17import java.util.*18import kotlin.collections.ArrayList19class TasksApi {20 private val sdf = SimpleDateFormat("yyyy-MM-dd")21 suspend fun createTask(22 token: String,23 taskDto: TaskDto,24 ) :TaskDto? {25 val (_, response, result) = Urls().getTaskUrl()26 .httpPost()27 .header("Authorization", "Bearer $token")28 .jsonBody(taskDto) // haven't checked if it is working29 .awaitStringResponseResult()30 val jsonBody = Gson().toJson(taskDto)31 Log.i(TAG, "Добавление задачи, тело запроса: $jsonBody")32 return result.fold(33 { data -> Gson().fromJson(data, TaskDto::class.java) },34 {35 Log.e(TAG, "Ошибка при создании задачи: ${it.exception.message}, ${response.statusCode}")36 return null37 }38 )39 }40 suspend fun deleteTask(41 token: String,42 taskDto: TaskDto,43 ) {44 val (_, response, result) = Urls().getTaskUrl(taskDto.uuid!!) // /task/{id}45 .httpDelete()46 .header("Authorization", "Bearer $token")47 .awaitStringResponseResult()48 return result.fold(49 { data -> Log.d(TAG, "Результат удаления: $data")},50 {51 Log.e(TAG, "Ошибка при удалении задачи: ${it.exception.message}, ${response.statusCode}")52 }53 )54 }55 suspend fun updateTask(56 token: String,57 taskDto: TaskDto,58 ) :TaskDto? {59 if (taskDto.uuid == null)60 return null61 val url = Urls().getTaskUrl(taskDto.uuid)62 val (_, response, result) = Urls().getTaskUrl(taskDto.uuid) // /task/{id}63 .httpPut()64 .header("Authorization", "Bearer $token")65 .jsonBody(taskDto) // haven't checked if it is working66 .awaitStringResponseResult()67 Log.d(TAG, url)68 return result.fold(69 { data -> Gson().fromJson(data, TaskDto::class.java) },70 {71 Log.e(TAG, "Ошибка при обновлении задачи: ${it.exception.message}, ${response.statusCode}")72 return null73 }74 )75 }76 suspend fun getAllTasks(token: String, startTime: Date?, endTime: Date?, label: String?): List<TaskDto> {77 val parameters = arrayListOf<Pair<String, Any?>>()78 if (startTime != null)79 parameters.add("dateFrom" to sdf.format(startTime))80 if (endTime != null)81 parameters.add("dateTo" to sdf.format(endTime))82 if (label != null)83 parameters.add("label" to label)84 val listType = object : TypeToken<ArrayList<TaskDto>?>() {}.type85 val (request, response, result) = Urls().getTaskUrl().httpGet(parameters)86 .header("Authorization", "Bearer $token")87 .awaitStringResponseResult()88 Log.i(TAG, "getAllTasks url=${request.url}")89 return result.fold(90 { data -> Gson().fromJson(data, listType) as ArrayList<TaskDto> },91 {92 Log.e(TAG, "Ошибка при запросе задач: ${it.exception.message}, ${response.statusCode}")93 return listOf()94 }95 )96 }97 private fun tasksResultHandler (98 result : Result<String, FuelError>,99 responseHandler: (result: ArrayList<TaskDto>) -> Unit?100 ) {101 when (result) {102 is Result.Failure -> {103 Log.i("ErrorMsg", result.getException().message ?: "")104 result.getException().stackTrace105 throw Exception(result.getException())106 }107 is Result.Success -> {108 val listType = object : TypeToken<ArrayList<TaskDto?>?>() {}.type109 val taskResult: ArrayList<TaskDto> = Gson().fromJson(result.get(), listType)110 responseHandler.invoke(taskResult)111 }112 }113 }114 companion object {115 private const val TAG = "TasksApi"116 }117}...

Full Screen

Full Screen

Client.kt

Source:Client.kt Github

copy

Full Screen

1package controller2import app.Config3import com.github.kittinunf.fuel.core.extensions.jsonBody4import com.github.kittinunf.fuel.httpDelete5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.httpPut8import com.github.kittinunf.fuel.json.FuelJson9import com.github.kittinunf.fuel.json.responseJson10import com.github.kittinunf.result.Result11import javafx.beans.property.SimpleStringProperty12import org.bouncycastle.jce.provider.BouncyCastleProvider13import tornadofx.*14import java.security.MessageDigest15import java.security.Security16import java.util.*17import javax.crypto.Cipher18import javax.crypto.spec.SecretKeySpec19open class ClientModule {20 lateinit var fetchRequest: ((String, String, p3: List<Pair<String, String>>?) -> FuelJson)21}22object Client {23 private val tokenProperty = SimpleStringProperty("")24 private var token by tokenProperty25 private lateinit var password: String26 fun settoken(t: String) { token = t }27 fun setpassword(p: String) { password = p }28 val Auth = AuthModule().apply { fetchRequest = ::fetchRequest }29 val Collections = CollectionsModule().apply { fetchRequest = ::fetchRequest }30 val Passwords = PasswordsModule().apply { fetchRequest = ::fetchRequest }31 private fun fetchRequest(path: String, _request: String, data: List<Pair<String, String>>? = null): FuelJson {32 val url = Config.url + path33 val request = when (_request) {34 "GET" -> url.httpGet()35 "POST" -> url.httpPost()36 "PUT" -> url.httpPut()37 "DELETE" -> url.httpDelete()38 else -> url.httpGet()39 }40 if (data != null) {41 val jsonData = with (JsonBuilder()) {42 for (p in data) {43 add(p.first, p.second)44 }45 build()46 }.toString()47 request.jsonBody(jsonData)48 }49 request.appendHeader(Pair("Authorization", token))50 val (_, response, result) = request.responseJson()51 if (result is Result.Failure) {52 var errStr: String53 if (response.statusCode == -1) {54 errStr = "{\"error\": \"${result.error.message}\"}"55 } else {56 errStr = String(response.data)57 }58 errStr = errStr.replace("\n", "")59 return FuelJson(errStr)60 }61 return result.get()62 }63 fun encryptIt(d: String): String {64 Security.addProvider(BouncyCastleProvider())65 val key = Base64.getEncoder().encodeToString(password.hashMe("SHA-256").toByteArray()).slice(0..31)66 val keyBytes: ByteArray = key.toByteArray(charset("UTF8"))67 val skey = SecretKeySpec(keyBytes, "AES")68 val input = d.toByteArray(charset("UTF8"))69 synchronized(Cipher::class.java) {70 val cipher = Cipher.getInstance("AES/ECB/PKCS7Padding")71 cipher.init(Cipher.ENCRYPT_MODE, skey)72 val cipherText = ByteArray(cipher.getOutputSize(input.size))73 var ctLength = cipher.update(74 input, 0, input.size,75 cipherText, 076 )77 ctLength += cipher.doFinal(cipherText, ctLength)78 return String(Base64.getEncoder().encode(cipherText))79 }80 }81 fun decryptIt(d: String): String {82 Security.addProvider(BouncyCastleProvider())83 val key = Base64.getEncoder().encodeToString(password.hashMe("SHA-256").toByteArray()).slice(0..31)84 val keyBytes = key.toByteArray(charset("UTF8"))85 val skey = SecretKeySpec(keyBytes, "AES")86 val input = org.bouncycastle.util.encoders.Base6487 .decode(d.trim { it <= ' ' }.toByteArray(charset("UTF8")))88 synchronized(Cipher::class.java) {89 val cipher = Cipher.getInstance("AES/ECB/PKCS7Padding")90 cipher.init(Cipher.DECRYPT_MODE, skey)91 val plainText = ByteArray(cipher.getOutputSize(input.size))92 var ptLength = cipher.update(input, 0, input.size, plainText, 0)93 ptLength += cipher.doFinal(plainText, ptLength)94 return String(plainText).trim { it <= ' ' }95 }96 }97}98fun String.hashMe(algo: String): String {99 val bytes = this.toByteArray()100 val md = MessageDigest.getInstance(algo)101 val digest = md.digest(bytes)102 return digest.fold("") { str, it -> str + "%02x".format(it) }103}...

Full Screen

Full Screen

Http.kt

Source:Http.kt Github

copy

Full Screen

1package com.fileee.oihAdapter.interpreter2import arrow.Kind3import arrow.core.Try4import arrow.core.left5import arrow.core.right6import arrow.effects.typeclasses.Async7import arrow.effects.typeclasses.milliseconds8import arrow.effects.typeclasses.seconds9import arrow.typeclasses.binding10import arrow.typeclasses.bindingCatch11import com.fileee.oihAdapter.Schedule12import com.fileee.oihAdapter.algebra.*13import com.github.kittinunf.fuel.core.FuelError14import com.github.kittinunf.fuel.core.Request15import com.github.kittinunf.fuel.core.Response16import com.github.kittinunf.fuel.httpDelete17import com.github.kittinunf.fuel.httpGet18import com.github.kittinunf.fuel.httpPost19import com.github.kittinunf.fuel.httpPut20import com.github.kittinunf.result.Result21typealias HttpFuelResp = Triple<Request, Response, Result<String, FuelError>>22/**23 * Interpreter for [HttpAlgebra]. This raises the constraint for [M] from [Monad] to [Async]. [Async] models24 * asynchronous behaviour and is a requirement for [Schedule].25 */26class HttpInterpreter<F>(27 val logAlgebra: LogAlgebra<F>,28 override val M: Async<F>29) : HttpAlgebra<F> {30 /**31 * Handles responses from Fuel, the http library used and retries for a certain amount of time on specific errors.32 *33 * @param tr A function to try and run which produces a [HttpFuelResp]34 */35 internal fun handleFuelResponse(tr: () -> Kind<F, HttpFuelResp>): Kind<F, HttpResponse> = M.bindingCatch {36 // below schedule equates to exponential backoff with the power of 2 and a base of 10ms till it reaches37 // 60 seconds, then it continues with one retry per minute up to five times38 Schedule.exponential(10.milliseconds).whileValue { it.lte(60.seconds) }39 .andThen(Schedule.spaced(60.seconds) * 5)40 // run the schedule with tr until it succeeds or the schedule ends41 .runS(M, tr).attempt().bind()42 .fold({ HttpException.UnhandledException(it).left() }, { (_, resp, res) ->43 res.fold({44 HttpResult(resp.statusCode, it).right()45 }, {46 HttpResult(resp.statusCode, it.response.responseMessage).right()47 })48 })49 }50 /**51 * Transforms a [Try<HttpFuelResp>] to a [Kind<F, HttpFuelResponse>] where [F] has an instance of [MonadError]52 * (which [Async] is extends)53 *54 * Raises errors for all retry-able error cases (Unhandled errors, usually connection issues), and rate-limit or service55 * unavailable error codes.56 * Everything else is accepted as either finished or non-retry-able.57 */58 internal fun Try<HttpFuelResp>.raiseRetryErrors() = fold({59 M.raiseError<HttpFuelResp>(it)60 }, { resp ->61 when (resp.second.statusCode) {62 403, 401 -> M.just(resp)63 429 -> M.raiseError(Exception("Rate limit reached"))64 503, 504 -> M.raiseError(Exception("Service unavailable"))65 else -> M.just(resp)66 }67 })68 override fun httpGet(path: String, headers: Map<String, String>): Kind<F, HttpResponse> =69 handleFuelResponse {70 M.binding {71 logAlgebra.debug("HttpGet to $path").bind()72 Try {73 path.httpGet()74 .header(headers)75 .responseString()76 }.raiseRetryErrors().bind()77 }78 }79 override fun httpPost(path: String, headers: Map<String, String>, body: String): Kind<F, HttpResponse> =80 handleFuelResponse {81 M.binding {82 logAlgebra.debug("HttpPost to $path").bind()83 Try {84 path.httpPost()85 .body(body)86 .header(headers + mapOf("Content-Type" to "application/json"))87 .responseString()88 }.raiseRetryErrors().bind()89 }90 }91 override fun httpPut(path: String, headers: Map<String, String>, body: String): Kind<F, HttpResponse> =92 handleFuelResponse {93 M.binding {94 logAlgebra.debug("HttpPut to $path").bind()95 Try {96 path.httpPut()97 .body(body)98 .header(headers + mapOf("Content-Type" to "application/json"))99 .responseString()100 }.raiseRetryErrors().bind()101 }102 }103 override fun httpDelete(path: String, headers: Map<String, String>): Kind<F, HttpResponse> =104 handleFuelResponse {105 M.binding {106 logAlgebra.debug("HttpDelete to $path").bind()107 Try {108 path.httpDelete()109 .header(headers)110 .responseString()111 }.raiseRetryErrors().bind()112 }113 }114}...

Full Screen

Full Screen

GMNetService.kt

Source:GMNetService.kt Github

copy

Full Screen

1package com.thierry.beaconfire.service2import android.content.Intent3import android.support.v4.content.LocalBroadcastManager4import android.util.Log5import android.webkit.CookieManager6import com.github.kittinunf.fuel.android.extension.responseJson7import com.github.kittinunf.fuel.core.Response8import com.github.kittinunf.fuel.httpDelete9import com.github.kittinunf.fuel.httpGet10import com.github.kittinunf.fuel.httpPost11import com.github.kittinunf.fuel.httpPut12import com.github.kittinunf.fuel.core.Manager13import com.thierry.beaconfire.App14import com.thierry.beaconfire.util.Constants15import org.jetbrains.anko.custom.async16import org.jetbrains.anko.uiThread17/** @brief Http状态枚举 */18enum class HttpStatusCode(val code: Int) {19 HttpStatusCodeSuccess(200),20 HttpStatusCodeError(500),21 HttpStatusCodeUnauthorized(403)22};23/** @brief Http方法枚举 */24enum class HttpMethod {25 HttpMethodGet,26 HttpMethodPost,27 HttpMethodPut,28 HttpMethodDelete,29};30/**31 * Created by Thierry on 16/2/25.32 */33class GMNetService private constructor() {34 val localBroadcastManager = LocalBroadcastManager.getInstance(App.instance);35 val cookieManager: CookieManager = CookieManager.getInstance()36 val TAG = GMNetService::class.java.canonicalName37 var apiHost: String = Constants.Host38 private object Holder {39 val INSTANCE = GMNetService()40 }41 companion object {42 val instance: GMNetService by lazy { Holder.INSTANCE }43 }44 fun doRequest(remoteUrl: String, method: HttpMethod, params: List<Pair<String, Any?>>?, success: (Response) -> Unit, failed: (String) -> Unit) {45 Log.d(TAG, remoteUrl)46 async {47 Manager.instance.baseHeaders = mapOf("Cookie" to cookieManager.getCookie(apiHost))48 when (method) {49 HttpMethod.HttpMethodGet ->50 remoteUrl.httpGet(params).responseJson { _, response, _ ->51 uiThread {52 handleResponse(response, success, failed)53 }54 }55 HttpMethod.HttpMethodPost ->56 remoteUrl.httpPost(params).responseJson { _, response, _ ->57 uiThread {58 handleResponse(response, success, failed)59 }60 }61 HttpMethod.HttpMethodDelete ->62 remoteUrl.httpDelete(params).responseJson { _, response, _ ->63 uiThread {64 handleResponse(response, success, failed)65 }66 }67 HttpMethod.HttpMethodPut ->68 remoteUrl.httpPut(params).responseJson { request, response, result ->69 uiThread {70 handleResponse(response, success, failed)71 }72 }73 }74 }75 }76 fun handleResponse(response: Response, success: (Response) -> Unit, failed: (String) -> Unit) {77 Log.d(TAG, "handleResponse")78 val statusCode = response.httpStatusCode79 if (statusCode == HttpStatusCode.HttpStatusCodeSuccess.code) {80 success(response)81 } else if (statusCode == HttpStatusCode.HttpStatusCodeUnauthorized.code) {82 Log.d(TAG, "HttpStatusCode.HttpStatusCodeUnauthorized")83 this.sendLoginExpired()84 } else {85 failed("Request Data Error")86 }87 }88 fun sendLoginExpired() {89 val intent: Intent = Intent()90 intent.action = Constants.Broadcast.LoginExpired91 localBroadcastManager.sendBroadcast(intent)92 }93}...

Full Screen

Full Screen

RestAPI.kt

Source:RestAPI.kt Github

copy

Full Screen

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

Full Screen

Full Screen

RepositoriesApiService.kt

Source:RepositoriesApiService.kt Github

copy

Full Screen

1package artifactory.api2import artifactory.api.model.PackageType3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.Response5import com.github.kittinunf.fuel.gson.jsonBody6import com.github.kittinunf.fuel.gson.responseObject7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.fuel.httpPut9import com.github.kittinunf.result.failure10import com.github.kittinunf.result.success11import com.google.gson.annotations.SerializedName12import com.synopsys.integration.log.Slf4jIntLogger13import org.slf4j.LoggerFactory14class RepositoriesApiService(fuelManager: FuelManager) : ArtifactoryApiService(fuelManager) {15 private val logger = Slf4jIntLogger(LoggerFactory.getLogger(javaClass))16 fun createRepository(key: String, repositoryType: RepositoryType, packageType: PackageType, remoteUrl: String = packageType.remoteUrl, externalDependenciesEnabled: Boolean = false): Response {17 val repositoryConfiguration = RepositoryConfiguration(key, repositoryType, packageType = packageType.packageType, remoteUrl = remoteUrl, externalDependenciesEnabled = externalDependenciesEnabled)18 return createRepository(repositoryConfiguration)19 }20 fun createRepository(repositoryConfiguration: RepositoryConfiguration): Response {21 return "/api/repositories/${repositoryConfiguration.key}".httpPut()22 .jsonBody(repositoryConfiguration)23 .response { response ->24 response.failure { logger.warn(it.exception.message) }25 response.success { logger.info("Successfully created repository '${repositoryConfiguration.key}") }26 }27 .join()28 .validate()29 }30 fun getRepository(repositoryKey: String): RepositoryConfiguration {31 return "/api/repositories/$repositoryKey".httpGet()32 .responseObject<RepositoryConfiguration>()33 .third.get()34 }35}36enum class RepositoryType {37 @SerializedName("local")38 LOCAL,39 @SerializedName("remote")40 REMOTE,41 @SerializedName("virtual")42 VIRTUAL,43}44data class RepositoryConfiguration(45 @SerializedName("key")46 val key: String,47 @SerializedName("rclass")48 val repositoryType: RepositoryType,49 @SerializedName("packageType")50 val packageType: String,51 @SerializedName("url")52 val remoteUrl: String?,53 @SerializedName("externalDependenciesEnabled")54 val externalDependenciesEnabled: Boolean = false55)...

Full Screen

Full Screen

TelegramAssignmentEndpoint.kt

Source:TelegramAssignmentEndpoint.kt Github

copy

Full Screen

1package com.ditcalendar.bot.ditCalendarServer.endpoint2import com.ditcalendar.bot.config.config3import com.ditcalendar.bot.config.dit_calendar_server_url4import com.ditcalendar.bot.ditCalendarServer.data.*5import com.github.kittinunf.fuel.core.extensions.authentication6import com.github.kittinunf.fuel.httpDelete7import com.github.kittinunf.fuel.httpGet8import com.github.kittinunf.fuel.httpPut9import com.github.kittinunf.fuel.serialization.responseObject10import com.github.kittinunf.result.Result11import kotlinx.serialization.builtins.list12import kotlinx.serialization.json.Json13import kotlinx.serialization.json.JsonConfiguration14class TelegramAssignmentEndpoint {15 private val config by config()16 private val ditCalendarUrl = config[dit_calendar_server_url]17 private val json = Json(JsonConfiguration.Stable.copy(ignoreUnknownKeys = true))18 fun readTasks(calendarId: Long, token: String): Result<TelegramTaskAssignments, Exception> =19 "$ditCalendarUrl/calendarentries/$calendarId/telegramlinks"20 .httpGet()21 .authentication().bearer(token)22 .responseObject(loader = TelegramTaskForAssignment.serializer().list, json = json)23 .third24 fun assignUserToTask(taskId: Long, telegramLink: TelegramLink, token: String): Result<TelegramTaskForUnassignment, Exception> =25 "$ditCalendarUrl/calendarentries/tasks/$taskId/assignment"26 .httpPut()27 .body(json.stringify(TelegramLink.serializer(), telegramLink))28 .authentication().bearer(token)29 .responseObject(loader = TelegramTaskForUnassignment.serializer(), json = json)30 .third31 fun unassignUserFromTask(taskId: Long, telegramLink: TelegramLink, token: String): Result<TelegramTaskAfterUnassignment, Exception> =32 "$ditCalendarUrl/calendarentries/tasks/$taskId/assignment"33 .httpDelete()34 .body(json.stringify(TelegramLink.serializer(), telegramLink))35 .authentication().bearer(token)36 .responseObject(loader = TelegramTaskAfterUnassignment.serializer(), json = json)37 .third38}...

Full Screen

Full Screen

HttpClient.kt

Source:HttpClient.kt Github

copy

Full Screen

1package net.ntworld.sentryIntegration.client2import com.github.kittinunf.fuel.core.FuelError3import com.github.kittinunf.fuel.core.Response4import com.github.kittinunf.fuel.httpGet5import com.github.kittinunf.fuel.httpPut6import net.ntworld.sentryIntegration.entity.Connection7import com.github.kittinunf.result.Result as FuelResult8internal class HttpClient(private val connection: Connection) {9 internal val baseUrl by lazy {10 if (connection.url.endsWith('/')) {11 connection.url.substring(0, connection.url.length - 1)12 } else {13 connection.url14 }15 }16 fun get(endpoint: String): String {17 val request = buildEndpointUrl(endpoint).httpGet()18 request.set("Authorization", "Bearer ${connection.token}")19 val (_, response, result) = request.responseString()20 return handleResultString(response, result)21 }22 fun put(endpoint: String, body: String): String {23 val request = buildEndpointUrl(endpoint).httpPut()24 request.set("Authorization", "Bearer ${connection.token}")25 request.set("Content-Type", "application/json")26 request.body(body)27 val (_, response, result) = request.responseString()28 return handleResultString(response, result)29 }30 private fun buildEndpointUrl(endpoint: String): String {31 return "$baseUrl/api/0$endpoint"32 }33 private fun handleResultString(response: Response, result: FuelResult<String, FuelError>): String {34 when (result) {35 is FuelResult.Failure -> {36 throw result.getException()37 }38 is FuelResult.Success -> {39 return result.get()40 }41 }42 }43}...

Full Screen

Full Screen

String.httpPut

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.Fuel2fun main(args: Array<String>) {3 )).responseString()4 println(request)5 println(response)6 println(result.get())7}8{9 "args": {}, 10 "files": {}, 11 "form": {12 }, 13 "headers": {14 },

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