Best Fuel code snippet using com.github.kittinunf.fuel.core.Blob
ServerApi.kt
Source:ServerApi.kt
...5import com.example.trafficgenerator.dto.GetTasksResponseDTO6import com.example.trafficgenerator.dto.KeepAliveResponseDTO7import com.example.trafficgenerator.dto.LoginResponseDTO8import com.example.trafficgenerator.dto.TaskDTO9import com.github.kittinunf.fuel.core.BlobDataPart10import com.github.kittinunf.fuel.core.FuelError11import com.github.kittinunf.fuel.core.FuelManager12import com.github.kittinunf.fuel.core.Request13import com.github.kittinunf.fuel.coroutines.awaitObjectResult14import com.github.kittinunf.fuel.httpGet15import com.github.kittinunf.fuel.httpPost16import com.github.kittinunf.fuel.httpUpload17import com.github.kittinunf.result.Result18import com.google.gson.Gson19import io.reactivex.disposables.Disposable20import ua.naiksoftware.stomp.Stomp21import ua.naiksoftware.stomp.StompClient22import ua.naiksoftware.stomp.dto.StompHeader23class ServerApi(private val context: Context, private val ipAddress: String) {24 private var listeningSocket: StompClient? = null25 private var listenForTasksTopic: Disposable? = null26 private val logTag: String = context.getString(R.string.server_api_tag)27 init {28 FuelManager.instance.basePath = "http://$ipAddress"29 }30 fun close() {31 stopListeningForTasks()32 disconnectListeningSocket()33 }34 private fun Request.addJsonBodyHeader(): Request =35 header("Content-Type" to "application/json")36 suspend fun register(username: String, password: String, name: String): Result<LoginResponseDTO, FuelError> {37 Log.i(logTag, "Registering new device: $name")38 val registerURL = context.getString(R.string.register)39 val bodyJson = Gson().toJson(40 mapOf(41 "login" to username,42 "password" to password,43 "name" to name44 )45 ).toString()46 return registerURL47 .httpPost()48 .addJsonBodyHeader()49 .body(bodyJson)50 .awaitObjectResult(LoginResponseDTO.Deserializer())51 }52 suspend fun login(username: String, password: String, uuid: String): Result<LoginResponseDTO, FuelError> {53 Log.i(logTag, "Logging in device: $uuid")54 val loginURL = context.getString(R.string.login)55 val bodyJson = Gson().toJson(56 mapOf(57 "login" to username,58 "password" to password,59 "uuid" to uuid60 )61 ).toString()62 return loginURL63 .httpPost()64 .addJsonBodyHeader()65 .body(bodyJson)66 .awaitObjectResult(LoginResponseDTO.Deserializer())67 }68 private fun Request.addAuthorizationHeader(token: String): Request =69 header("Authorization" to "Bearer $token")70 private fun Request.addUUIDHeader(uuid: String): Request =71 header("device-uuid" to uuid)72 suspend fun getTasks(token: String, uuid: String): Result<Array<GetTasksResponseDTO>, FuelError> {73 Log.i(logTag, "Getting tasks for device: $uuid")74 val getTasksURL = context.getString(R.string.get_tasks)75 return getTasksURL76 .httpGet()77 .addJsonBodyHeader()78 .addAuthorizationHeader(token)79 .addUUIDHeader(uuid)80 .awaitObjectResult(GetTasksResponseDTO.ArrayDeserializer())81 }82 private fun connectListeningSocket(token: String) {83 if (listeningSocket == null) {84 Log.i(logTag, "Creating listening socket")85 listeningSocket = Stomp.over(86 Stomp.ConnectionProvider.OKHTTP,87 "ws://$ipAddress${context.getString(R.string.device_web_socket)}"88 )89 }90 if (listeningSocket?.isConnected == false) {91 Log.i(logTag, "Connecting listening socket")92 listeningSocket?.connect(listOf(StompHeader("Authorization", "Bearer $token")))93 }94 }95 private fun disconnectListeningSocket() {96 Log.i(logTag, "Disconnecting listening socket")97 listeningSocket?.disconnect()98 }99 fun listenForTasks(token: String, uuid: String, callback: (TaskDTO, String, String) -> (Unit)) {100 connectListeningSocket(token)101 Log.i(logTag, "Listening for tasks")102 listenForTasksTopic =103 listeningSocket?.topic(context.getString(R.string.listen_for_tasks).format(uuid))?.subscribe { data ->104 Log.i(logTag, "Received task")105 callback(TaskDTO.Deserializer().deserialize(data.payload), uuid, token)106 }107 }108 fun stopListeningForTasks() {109 Log.i(logTag, "Stopping listening for tasks")110 listenForTasksTopic?.dispose()111 }112 suspend fun uploadTaskResult(113 token: String,114 uuid: String,115 task: GetTasksResponseDTO116 ): Result<GetTasksResponseDTO, FuelError> {117 Log.i(logTag, "Uploading task result to server")118 val uploadTaskResultURL = context.getString(R.string.upload_task_result).format(task.id)119 val fileStream = GetTasksResponseDTO.Serializer().serialize(task).byteInputStream()120 return uploadTaskResultURL121 .httpUpload()122 .add(BlobDataPart(fileStream, name = "file", filename = "task_${task.id}_result.json"))123 .addAuthorizationHeader(token)124 .addUUIDHeader(uuid)125 .awaitObjectResult(GetTasksResponseDTO.Deserializer())126 }127 suspend fun sendKeepAlive(token: String, uuid: String): Result<KeepAliveResponseDTO, FuelError> {128 val keepAliveURL = context.getString(R.string.active)129 return keepAliveURL130 .httpPost()131 .addAuthorizationHeader(token)132 .addUUIDHeader(uuid)133 .awaitObjectResult(KeepAliveResponseDTO.Deserializer())134 }135}...
Api.kt
Source:Api.kt
...21 val request = Fuel.upload(base + "addStickerToSet", Method.POST, listOf(22 "user_id" to params.userId,23 "name" to params.name,24 "emojis" to params.emojis))25 .add(BlobDataPart(params.pngSticker, "png_sticker", "image.png", contentType = "image/png"))26 val (_, result) = getResponse<Boolean>(request)27 if (result is Result.Failure) {28 println(result.error)29 return null30 }31 val response = result.get()32 if (!response.ok) return null33 return response.result34 }35 fun createNewStickerSet(params: TCreateNewStickerSetParams): Boolean? {36 val request = Fuel.upload(base + "createNewStickerSet", Method.POST, listOf(37 "user_id" to params.userId,38 "name" to params.name,39 "title" to params.title,40 "emojis" to params.emojis))41 .add(BlobDataPart(params.pngSticker, "png_sticker", "image.png", contentType = "image/png"))42 val (_, result) = getResponse<Boolean>(request)43 if (result is Result.Failure) {44 println(result.error)45 return null46 }47 val response = result.get()48 if (!response.ok) return null49 return response.result50 }51 fun sendPhoto(chatId: Long, imageStream: InputStream): TMessage? {52 val request = Fuel.upload(base + "sendPhoto", Method.POST, listOf("chat_id" to chatId))53 .add(BlobDataPart(imageStream, "photo", "image.png", contentType = "image/png"))54 val (_, result) = getResponse<TMessage>(request)55 if (result is Result.Failure) {56 println(result.error)57 return null58 }59 val response = result.get()60 if (!response.ok) return null61 return response.result62 }63 private inline fun <reified ResultType: Any> sendRequest(route: String, params: Any? = null, image: BlobDataPart? = null): ResultType? {64 val serializedParams = gson.toJson(params)65 var request = Fuel.post(base + route)66 if (params != null) {67 request = request68 .header("Content-Type", "application/json")69 .body(serializedParams)70 }71 val (res, result) = getResponse<ResultType>(request)72 if (result is Result.Failure) {73 println(res.body().asString("text/plain"))74 println(result.error)75 return null76 }77 val response = result.get()...
MyPageActivity.kt
Source:MyPageActivity.kt
...13import android.graphics.Bitmap14import android.graphics.Path15import android.util.Log16import com.github.kittinunf.fuel.Fuel17import com.github.kittinunf.fuel.core.Blob18import com.github.kittinunf.fuel.core.DataPart19import com.github.kittinunf.fuel.core.interceptors.loggingResponseInterceptor20import okhttp3.MultipartBody21import java.io.File22class MyPageActivity : AppCompatActivity() {23 val RESULT_LOAD_IMAGE = 124 lateinit var img: ImageView25 override fun onCreate(savedInstanceState: Bundle?) {26 super.onCreate(savedInstanceState)27 setContentView(R.layout.activity_my_page)28 img = findViewById(R.id.profile_image_view)29 img.setOnClickListener {30 val i = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)31 startActivityForResult(i, RESULT_LOAD_IMAGE)...
FuelService.kt
Source:FuelService.kt
...15 fun uploadAnonFile(selectedFile: InputStream, fileName: String?): UploadRequest {16 val url = baseUri + "file";17 val setFileName = if (fileName !== null) fileName else "file";18 return Fuel.upload(url, method = Method.POST, parameters = listOf("name" to setFileName))19 .add(BlobDataPart(selectedFile, name = "file", filename = setFileName));20 }21 fun uploadFile(selectedFile: InputStream, fileName: String?, authKey: String): UploadRequest {22 val url = baseUri + "file";23 val setFileName = if (fileName !== null) fileName else "file";24 val authKeyCookie = "${authKeyCookie}=${authKey}";25 return Fuel.upload(url, method = Method.POST, parameters = listOf("name" to setFileName))26 .header(Headers.COOKIE to authKeyCookie).upload()27 .add(BlobDataPart(selectedFile, name = "file", filename = setFileName))28 }29 fun getFiles(authKey: String): Request {30 val url = "${baseUri}/user/files"31 val authKeyCookie = "${authKeyCookie}=${authKey}";32 return Fuel.get(url, parameters = listOf("page" to 0, "limit" to 1000))33 .header(Headers.COOKIE to authKeyCookie)34 }35 fun loginUser(username: String, password: String): Request {36 val url ="${baseUri}/user/login"37 return Fuel.post(url, parameters = listOf("username" to username, "password" to password));38 }39 fun deleteFile(id: String, authKey: String): Request {40 val url ="${baseUri}/file/${id}"41 val authKeyCookie = "${authKeyCookie}=${authKey}";...
createAttachment.kt
Source:createAttachment.kt
1package by.dev.madhead.doktor.confluence2import by.dev.madhead.doktor.model.Attachment3import by.dev.madhead.doktor.model.ResolvedConfluenceServer4import by.dev.madhead.doktor.model.confluence.CreateAttachmentResponse5import com.github.kittinunf.fuel.core.Blob6import com.github.kittinunf.fuel.httpUpload7import com.github.kittinunf.fuel.rx.rx_object8import com.github.kittinunf.result.Result9import com.google.gson.Gson10import io.reactivex.Single11import java.net.URL12fun createAttachment(confluenceServer: ResolvedConfluenceServer, id: String, attachment: Attachment): Single<CreateAttachmentResponse> {13 return URL(URL(confluenceServer.url).toExternalForm() + "/rest/api/content/${id}/child/attachment").toString()14 .httpUpload()15 .apply {16 if (!confluenceServer.user.isNullOrBlank()) {17 authenticate(confluenceServer.user!!, confluenceServer.password ?: "")18 }19 }20 .blob { request, _ ->21 request.name = "file"22 Blob(attachment.fileName, attachment.bytes.size.toLong(), { attachment.bytes.inputStream() })23 }24 .header("X-Atlassian-Token" to "nocheck")25 .rx_object(CreateAttachmentResponse.Deserializer())26 .flatMap {27 when (it) {28 is Result.Success -> Single.just(it.value)29 is Result.Failure -> {30 try {31 val exception = Gson().fromJson(it.error.response.data.toString(Charsets.UTF_8), ConfluenceException::class.java)32 if (!exception.message.isBlank()) {33 Single.error<CreateAttachmentResponse>(exception)34 } else {35 throw IllegalArgumentException()36 }...
integrationTest.gradle.kts
Source:integrationTest.gradle.kts
1plugins {2 `java-library`3 kotlin("jvm")4 // https://github.com/avast/gradle-docker-compose-plugin5 id("com.avast.gradle.docker-compose") version "0.14.3"6 // https://github.com/kotest/kotest-gradle-plugin7 id("io.kotest") version "0.3.8"8}9repositories {10 mavenCentral()11 // jitpack required by Fuel12 maven(url = "https://jitpack.io") {13 name = "jitpack"14 }15}16val bootJar = tasks.getByPath(":web:bootJar")17val test by tasks.getting(Test::class) {18 useJUnitPlatform { }19}20val composeUp = tasks.getByName("composeUp")21composeUp.dependsOn(bootJar)22dockerCompose.isRequiredBy(test)23dependencies {24 // Kotlin25 implementation(kotlin("stdlib-jdk8"))26 // KoTest: https://github.com/kotest/kotest27 testImplementation("io.kotest:kotest-runner-junit5-jvm:4.6.0")28 testImplementation("io.kotest:kotest-assertions-core-jvm:4.6.0")29 // Fuel HTTP library: https://github.com/kittinunf/fuel30 testImplementation("com.github.kittinunf.fuel:fuel:2.0.1")31 // Fuel Jackson (de)serializer: https://github.com/kittinunf/fuel/blob/master/fuel-jackson/README.md32 testImplementation("com.github.kittinunf.fuel:fuel-jackson:2.0.1")33 // Jackson support for Java time classes: https://github.com/FasterXML/jackson-modules-java834 testImplementation("com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.0")35 testImplementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.9.0")36 testImplementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.0")37 implementation(project(":dto"))38}...
ImageProvider.kt
Source:ImageProvider.kt
1package fr.niels.epicture.provider2import android.util.Log3import com.github.kittinunf.fuel.Fuel4import com.github.kittinunf.fuel.core.BlobDataPart5import com.github.kittinunf.result.Result6import fr.niels.epicture.utils.IMGUR_API_URL7import java.io.InputStream8class ImageProvider {9 private val tag = "ImageProvider"10 fun upload(imageUri: InputStream) {11 Fuel.upload(IMGUR_API_URL + "3/image")12 .add(13 BlobDataPart(imageUri, name = "image")14 )15 .response { result ->16 if (result is Result.Failure) {17 Log.e(tag, "Invalid request: $result")18 }19 }20 }21 fun favorite(imageHash: String) {22 Fuel.upload(IMGUR_API_URL + "3/image/$imageHash/favorite")23 .response { result ->24 Log.e(tag, "Request: $result")25 if (result is Result.Failure) {26 Log.e(tag, "Invalid request: $result")27 }...
BallchasingReplayForwarder.kt
Source:BallchasingReplayForwarder.kt
1package com.x7ff.rl.replay.api.forwarder2import com.github.kittinunf.fuel.core.BlobDataPart3import com.github.kittinunf.fuel.core.Headers4import com.github.kittinunf.fuel.httpUpload5import java.io.ByteArrayInputStream6class BallchasingReplayForwarder: ReplayForwarder() {7 companion object {8 private val API_KEY = System.getenv("BALLCHASING_API_KEY") ?: throw IllegalStateException("BALLCHASING_API_KEY environment variable missing")9 }10 override fun forwardReplay(fileName: String, bytes: ByteArray) {11 println("[Ballchasing] Forwarding '${fileName}'...")12 val (_, resp) = "https://ballchasing.com/api/v2/upload?visibility=public".httpUpload()13 .add { BlobDataPart(ByteArrayInputStream(bytes), name = "file", filename = fileName, contentType = "application/octet-stream") }14 .header(Headers.AUTHORIZATION, API_KEY)15 .response()16 println("[Ballchasing] Status code for '${fileName}': ${resp.statusCode}")17 }18}...
Blob
Using AI Code Generation
1val (request, response, result) = Fuel.get("README.md").responseBlob()2val (request, response, result) = Fuel.get("README.md").responseString()3val (request, response, result) = Fuel.get("README.md").responseString()4val (request, response, result) = Fuel.get("README.md").responseByteArray()5val (request, response, result) = Fuel.get("README.md").responseStream()6val (request, response, result) = Fuel.get("README.md").responseReader()7val (request, response, result) = Fuel.get("README.md").responseFile()8val (request, response, result) = Fuel.get("README.md").responseFile()9val (request, response, result) = Fuel.get("README
Blob
Using AI Code Generation
1val data = result.component1()!!.data2val blob = Blob(data, "image/png")3val data = result.component1()!!.data4val blob = Blob(data, "image/png")5val data = result.component1()!!.data6val blob = Blob(data, "image/png")7val data = result.component1()!!.data8val blob = Blob(data, "image/png")9val data = result.component1()!!.data10val blob = Blob(data, "image/png")11val data = result.component1()!!.data12val blob = Blob(data, "image/png")13val data = result.component1()!!.data14val blob = Blob(data, "image/png")15val data = result.component1()!!.data16val blob = Blob(data, "image/png")17val (
Blob
Using AI Code Generation
1 val imageBlob = Blob("image/jpeg", imageByteArray)2 .add(imageBlob)3 .response { result ->4 }5 val imageBlob = Blob("image/jpeg", imageByteArray)6 .add(imageBlob)7 .response { result ->8 }
Blob
Using AI Code Generation
1 val blob = Blob("name", "image/png", File("/path/to/image.png").readBytes())2 val (request, response, result) = Fuel.upload("/upload")3 .add(blob)4 .responseString()5 println(request)6 println(response)7 println(result)8 }9}10The first one uses the Fuel.upload() method, while the
Blob
Using AI Code Generation
1 }.blob("image", File("path/to/image/file"))2 }3 fun downloadBlob() {4 File.createTempFile("downloaded", ".jpeg")5 }.blob()6 }7 fun downloadBlobWithProgress() {8 File.createTempFile("downloaded", ".jpeg")9 }.progress { readBytes, totalBytes ->10 }.blob()11 }12 fun uploadBlobWithProgress() {13 }.progress { writtenBytes, totalBytes ->14 }.blob("image", File("path/to/image/file"))15 }16}17blob(name: String): It returns the Blob
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!!