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

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

Uploader.kt

Source:Uploader.kt Github

copy

Full Screen

1package com.github.wakingrufus.website.lib2import com.beust.klaxon.JsonArray3import com.beust.klaxon.JsonObject4import com.beust.klaxon.Parser5import com.github.kittinunf.fuel.core.FileDataPart6import com.github.kittinunf.fuel.core.ResponseDeserializable7import com.github.kittinunf.fuel.core.extensions.authentication8import com.github.kittinunf.fuel.httpGet9import com.github.kittinunf.fuel.httpUpload10import com.github.kittinunf.result.Result11import com.github.kittinunf.result.map12import com.github.wakingrufus.website.WebsiteDsl13import mu.KLogging14import java.io.File15import java.io.InputStream16@WebsiteDsl17interface Uploader {18 fun upload(baseDir: File, file: File)19 fun check(baseDir: File, file: File): Boolean20}21class NeocitiesUploader(val username: String, val password: String) : Uploader {22 companion object : KLogging()23 private val existingFiles: NeocitiesFileList by lazy {24 "https://neocities.org/api/list"25 .httpGet()26 .authentication().basic(username, password)27 .responseObject(KlaxonDeserializer()).third.map {28 NeocitiesFileList(29 result = it.string("result") ?: "",30 files = it.array<JsonObject>("files").orEmpty().map {31 NeocitiesFile(32 path = it.string("path").orEmpty(),33 size = it.long("size") ?: 0L,34 sha1Hash = it.string("sha1_hash").orEmpty()35 )36 })37 }.get()38 }39 override fun upload(baseDir: File, file: File) {40 logger.info("Uploading file: ${file.toRelativeString(baseDir)}")41 "https://neocities.org/api/upload"42 .httpUpload()43 .add(FileDataPart(name = file.toRelativeString(baseDir), file = file))44 .authentication().basic(username, password)45 .responseString().let { (request, response, result) ->46 when (result) {47 is Result.Failure -> {48 logger.error(49 "error uploading: ${String(result.getException().errorData)}",50 result.getException().exception51 )52 }53 is Result.Success -> {54 logger.info { result.get() }55 }56 }57 }58 }59 override fun check(baseDir: File, file: File): Boolean {60 return checkNeoCitiesFile(baseDir, existingFiles, file)61 }62}63fun neocities(username: String, password: String): Uploader {64 return NeocitiesUploader(username = username, password = password)65}66fun neocities(apiKey: String): Uploader {67 return NeocitiesAPiKeyUploader(apiKey = apiKey)68}69class NeocitiesAPiKeyUploader(val apiKey: String) : Uploader {70 companion object : KLogging()71 private val existingFiles: NeocitiesFileList by lazy {72 "https://neocities.org/api/list"73 .httpGet()74 .header("Authorization" to "Bearer $apiKey")75 .responseObject(KlaxonDeserializer()).third.map {76 NeocitiesFileList(77 result = it.string("result") ?: "",78 files = it.array<JsonObject>("files").orEmpty().map {79 NeocitiesFile(80 path = it.string("path").orEmpty(),81 size = it.long("size") ?: 0L,82 sha1Hash = it.string("sha1_hash").orEmpty()83 )84 })85 }.get()86 }87 override fun check(baseDir: File, file: File): Boolean {88 return checkNeoCitiesFile(baseDir, existingFiles, file)89 }90 override fun upload(baseDir: File, file: File) {91 logger.info("Uploading file: ${file.toRelativeString(baseDir)}")92 "https://neocities.org/api/upload"93 .httpUpload()94 .add(FileDataPart(name = file.toRelativeString(baseDir), file = file))95 .header("Authorization" to "Bearer $apiKey")96 .responseString().let { (request, response, result) ->97 when (result) {98 is Result.Failure -> {99 logger.error(100 "error uploading: ${String(result.getException().errorData)}",101 result.getException().exception102 )103 }104 is Result.Success -> {105 logger.info { result.get() }106 }107 }108 }109 }110}111class NeocitiesTestUploader(val apiKey: String) : Uploader {112 companion object : KLogging()113 private val existingFiles: NeocitiesFileList by lazy {114 "https://neocities.org/api/list"115 .httpGet()116 .header("Authorization" to "Bearer $apiKey")117 .responseObject(KlaxonDeserializer()).third.map {118 NeocitiesFileList(119 result = it.string("result") ?: "",120 files = it.array<JsonObject>("files").orEmpty().map {121 NeocitiesFile(122 path = it.string("path").orEmpty(),123 size = it.long("size") ?: 0L,124 sha1Hash = it.string("sha1_hash").orEmpty()125 )126 })127 }.get()128 }129 override fun check(baseDir: File, file: File): Boolean {130 return checkNeoCitiesFile(baseDir, existingFiles, file)131 }132 override fun upload(baseDir: File, file: File) {133 logger.info("NOT Uploading file: ${file.toRelativeString(baseDir)}")134 }135}136class KlaxonDeserializer : ResponseDeserializable<JsonObject> {137 override fun deserialize(inputStream: InputStream): JsonObject? {138 return Parser.default().parse(inputStream) as? JsonObject139 }140}141class KlaxonArrayDeserializer : ResponseDeserializable<JsonArray<JsonObject>> {142 override fun deserialize(inputStream: InputStream): JsonArray<JsonObject>? {143 return Parser.default().parse(inputStream) as? JsonArray<JsonObject>144 }145}...

Full Screen

Full Screen

ServerApi.kt

Source:ServerApi.kt Github

copy

Full Screen

1package com.example.trafficgenerator.serverapi2import android.content.Context3import android.util.Log4import com.example.trafficgenerator.R5import 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}...

Full Screen

Full Screen

FuelHttp.kt

Source:FuelHttp.kt Github

copy

Full Screen

1package com.gavindon.mvvm_lib.net2import android.annotation.SuppressLint3import com.gavindon.mvvm_lib.utils.GsonUtil4import com.gavindon.mvvm_lib.utils.Parameters5import com.gavindon.mvvm_lib.utils.onFailed6import com.gavindon.mvvm_lib.utils.onSuccessT7import com.github.kittinunf.fuel.core.FileDataPart8import com.github.kittinunf.fuel.httpGet9import com.github.kittinunf.fuel.httpPost10import com.github.kittinunf.fuel.httpUpload11import com.github.kittinunf.fuel.rx.rxResponseString12import com.google.gson.JsonSyntaxException13import com.orhanobut.logger.Logger14import io.reactivex.Observable15import io.reactivex.Single16import io.reactivex.android.schedulers.AndroidSchedulers17import io.reactivex.disposables.CompositeDisposable18import io.reactivex.disposables.Disposable19import io.reactivex.schedulers.Schedulers20import java.io.File21import java.lang.reflect.Type22/**23 * description:24 * Created by liNan on 2019/12/19 10:2725 */26class FuelHttp private constructor() : IFuelHttp {27 private val mCompositeDisposable: CompositeDisposable by lazy { CompositeDisposable() }28 companion object {29 val instance: FuelHttp by lazy(LazyThreadSafetyMode.PUBLICATION) {30 FuelHttp()31 }32 }33 override val compositeDisposable: CompositeDisposable = mCompositeDisposable34 override fun get(url: String, param: Parameters?): Single<String> {35 return url.httpGet(param)36 .rxResponseString()37 .compose(RxScheduler.applySingleScheduler())38 .compose(RxScheduler.applySingleLoading())39 }40 override fun post(url: String, param: Parameters?): Single<String> {41 return url.httpPost(param)42 .rxResponseString()43 .compose(RxScheduler.applySingleScheduler())44 .compose(RxScheduler.applySingleLoading())45 }46 override fun postWithoutLoading(url: String, param: Parameters?): Single<String> {47 return url.httpPost(param)48 .rxResponseString()49 .compose(RxScheduler.applySingleScheduler())50 }51 override fun upload(url: String, files: List<File>, param: Parameters?): Single<String> {52 val dataParts = files.map { FileDataPart(it) }53 /*url.httpUpload().add(dataParts.toTypedArray().iterator().next())54 .rxResponseString()55 .compose(RxScheduler.applySingleScheduler())56 .compose(RxScheduler.applySingleLoading())*/57 return url.httpUpload().plus(dataParts).rxResponseString()58 .compose(RxScheduler.applySingleScheduler())59 .compose(RxScheduler.applySingleLoading())60 }61 override fun getWithoutLoading(url: String, param: Parameters?): Single<String> {62 return url.httpGet(param)63 .rxResponseString()64 .compose(RxScheduler.applySingleScheduler())65 }66 override fun <T> getMerge(vararg args: Observable<T>) {67 val observables = args.toList()68 Observable.merge(observables).observeOn(Schedulers.io())69 .subscribeOn(AndroidSchedulers.mainThread())70 .subscribe()71 }72 override73 fun getSingle(url: String, param: Parameters?, method: Method): Single<String> {74 return if (method.value == Method.GET.value) {75 url.httpGet(param).rxResponseString()76 } else {77 url.httpPost(param).rxResponseString()78 }79 }80}81@SuppressLint("CheckResult")82inline fun <reified T> Single<String>.parse(83 type: Type,84 crossinline onSuccess: onSuccessT<T>,85 crossinline onFailed: onFailed86) {87 this.subscribe({88 val p = GsonUtil.str2Obj<T>(it, type)89 if (null != p) {90 //反参解析正常91 onSuccess(p)92 } else {93 //如果返回解析数据为null则代表json解析异常94 onFailed(JsonSyntaxException("json异常"))95 }96 Logger.json(it)97 }, {98 Logger.e(it, "http异常")99 onFailed(it)100 })101}102inline fun <reified T> Single<String>.parse2(103 type: Type,104 crossinline onSuccess: onSuccessT<T>,105 crossinline onFailed: onFailed106): Disposable {107 return subscribe({108 val p = GsonUtil.str2Obj<T>(it, type)109 //反参解析正常110 if (p != null) {111 onSuccess.invoke(p)112 } else {113 //如果返回解析数据为null则代表json解析异常114 onFailed(JsonSyntaxException("json异常"))115 }116 Logger.json(it)117 }, {118 Logger.e(it, "http异常")119 onFailed(it)120 })121}122/**123 * 投诉建议 使用124 */125inline fun <reified T> Observable<String>.parse(126 type: Type,127 crossinline onSuccess: onSuccessT<T>,128 crossinline onFailed: onFailed129): Disposable {130 return this.subscribe({131 val p = GsonUtil.str2Obj<T>(it, type)132 if (null != p) {133 //反参解析正常134 onSuccess(p)135 } else {136 //如果返回解析数据为null则代表json解析异常137 onFailed(JsonSyntaxException("json异常"))138 }139 Logger.json(it)140 }, {141 Logger.e(it, "http返回异常")142 onFailed(it)143 })144}...

Full Screen

Full Screen

UploadTask.kt

Source:UploadTask.kt Github

copy

Full Screen

1package xyz.sangcomz.gradle2import com.github.kittinunf.fuel.core.FileDataPart3import com.github.kittinunf.fuel.core.Parameters4import com.github.kittinunf.fuel.core.isSuccessful5import com.github.kittinunf.fuel.httpUpload6import org.gradle.api.DefaultTask7import org.gradle.api.tasks.TaskAction8import java.io.*9import java.util.regex.Pattern10import java.util.zip.ZipEntry11import java.util.zip.ZipOutputStream12open class UploadTask : DefaultTask() {13 init {14 group = "slack file upload"15 description = "File Uploader"16 }17 @TaskAction18 fun task() {19 val slackUploadPluginExtension =20 project.extensions.getByType(SlackUploadPluginExtension::class.java)21 val uploadFile = if (!slackUploadPluginExtension.filePaths.isNullOrEmpty()) {22 zip(23 slackUploadPluginExtension.filePaths!!,24 slackUploadPluginExtension.zipName,25 slackUploadPluginExtension.zipFilePath26 )27 } else {28 File(slackUploadPluginExtension.filePath)29 }30 uploadFile(31 uploadFile,32 getParameters(slackUploadPluginExtension),33 slackUploadPluginExtension.deleteZipFileAfterUpload34 )35 }36 private fun uploadFile(file: File, parameters: Parameters, isZipFileDeleteAfterUpload: Boolean) {37 "https://slack.com/api/files.upload"38 .httpUpload(parameters)39 .add(40 FileDataPart(file, "file")41 )42 .response { request, response, result ->43 result.fold({44 if (isZipFileDeleteAfterUpload45 && file.extension.isExtensionZip()46 )47 file.delete()48 println(response.body().asString("application/json"))49 }, {50 println(it)51 })52 }.get()53 }54 private fun getParameters(slackUploadPluginExtension: SlackUploadPluginExtension): ArrayList<Pair<String, Any>> {55 val token = slackUploadPluginExtension.token ?: run {56 throw IllegalArgumentException("token is null")57 }58 return arrayListOf<Pair<String, Any>>().apply {59 add("token" to token)60 slackUploadPluginExtension.channels?.let {61 add("channels" to it)62 }63 slackUploadPluginExtension.initialComment?.let {64 add("initial_comment" to it)65 }66 slackUploadPluginExtension.title?.let {67 add("title" to it)68 }69 }70 }71 private fun zip(files: Array<String>, zipFileName: String?, zipFilePath: String?): File {72 val name = "${zipFileName ?: "upload"}.zip"73 val path = if (zipFilePath.isNullOrEmpty()) "" else "$zipFilePath/"74 File(path).mkdirs()75 ZipOutputStream(BufferedOutputStream(FileOutputStream(path + name))).use { out ->76 val data = ByteArray(1024)77 for (file in files) {78 FileInputStream(file).use { fi ->79 BufferedInputStream(fi).use { origin ->80 val entry = ZipEntry(file)81 out.putNextEntry(entry)82 while (true) {83 val readBytes = origin.read(data)84 if (readBytes == -1) {85 break86 }87 out.write(data, 0, readBytes)88 }89 }90 }91 }92 }93 return File(path + name)94 }95 private fun String.isExtensionZip() = this == "zip"96}...

Full Screen

Full Screen

CurseForgeClient.kt

Source:CurseForgeClient.kt Github

copy

Full Screen

1package mod.lucky.tools.uploadToCurseForge2import com.github.kittinunf.fuel.core.FileDataPart3import com.github.kittinunf.fuel.core.InlineDataPart4import kotlinx.serialization.*5import kotlinx.serialization.json.*6import com.github.kittinunf.fuel.httpGet7import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult8import com.github.kittinunf.fuel.httpUpload9import com.github.kittinunf.result.Result10import java.io.File11import java.util.logging.Logger12@Serializable13data class CurseForgeGameDependency(14 val id: Int,15 val name: String,16 val slug: String,17)18@Serializable19data class CurseForgeGameVersion(20 val id: Int,21 val gameVersionTypeID: Int,22 val name: String,23 val slug: String,24)25enum class CurseForgeGameVersionType(val id: Int) {26 MINECRAFT(1),27 JAVA(2),28 FORGE(3),29 FABRIC_LOADER(73247),30 LOADER_TYPE(68441), // Forge, Fabric, Rift31}32fun getCurseForgeLoaderType(loader: LuckyBlockLoader): String {33 return when(loader) {34 LuckyBlockLoader.FORGE -> "Forge"35 LuckyBlockLoader.FABRIC -> "Fabric"36 }37}38@Serializable39data class CurseForgeUploadMetadata(40 val changelog: String, // Can be HTML or markdown if changelogType is set.41 val changelogType: String = "text", // One of "text", "html", "markdown"42 val displayName: String? = null, // Optional: A friendly display name used on the site if provided.43 val parentFileID: Int? = null, // Optional: The parent file of this file.44 val gameVersions: List<Int>, // A list of supported game versions, see the Game Versions API for details. Not supported if parentFileID is provided.45 val releaseType: String, // One of "alpha", "beta", "release".46)47class CurseForgeClient(private val token: String) {48 private val logger = Logger.getLogger(this.javaClass.name)49 private val LUCKY_BLOCK_PROJECT_ID = 57682550 suspend fun httpGet(endpoint: String): String {51 val (_, _, result) = "https://minecraft.curseforge.com${endpoint}"52 .httpGet()53 .header(mapOf("X-Api-Token" to token))54 .awaitStringResponseResult()55 when (result) {56 is Result.Failure -> {57 throw result.getException()58 }59 is Result.Success -> {60 return result.get()61 }62 }63 }64 suspend fun getGameDependencies(): List<CurseForgeGameDependency> {65 // TODO: Currently this API endpoint is broken66 logger.info("Fetching game dependencies from CurseForge")67 return Json.decodeFromString(httpGet("/api/game/dependencies"))68 }69 suspend fun getGameVersions(): List<CurseForgeGameVersion> {70 logger.info("Fetching game versions from CurseForge")71 return Json.decodeFromString(httpGet("/api/game/versions"))72 }73 suspend fun uploadDist(jarFile: File, metadata: CurseForgeUploadMetadata) {74 logger.info("Uploading file to CurseForge, file=${jarFile}, metadata=${metadata}")75 val (_, response, result) = "https://minecraft.curseforge.com/api/projects/${LUCKY_BLOCK_PROJECT_ID}/upload-file"76 .httpUpload()77 .add(FileDataPart.from(jarFile.path, name="file"))78 .add(InlineDataPart(Json.encodeToString(metadata), contentType = "application/json", name = "metadata"))79 .header(mapOf("X-Api-Token" to token))80 .awaitStringResponseResult()81 when (result) {82 is Result.Failure -> {83 logger.severe(String(response.data))84 throw result.getException()85 }86 is Result.Success -> return87 }88 }89}...

Full Screen

Full Screen

Fuel.kt

Source:Fuel.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Parameters5import com.github.kittinunf.fuel.core.Request6import com.github.kittinunf.fuel.core.RequestFactory7import com.github.kittinunf.fuel.core.requests.DownloadRequest8import com.github.kittinunf.fuel.core.requests.UploadRequest9object Fuel : RequestFactory.Convenience by FuelManager.instance {10 var trace = false11 fun trace(function: () -> String) {12 @Suppress("ConstantConditionIf")13 if (trace) println(function())14 }15 fun reset() = FuelManager.instance.reset()16}17fun String.httpGet(parameters: Parameters? = null): Request =18 Fuel.get(this, parameters)19fun RequestFactory.PathStringConvertible.httpGet(parameter: Parameters? = null): Request =20 this.path.httpGet(parameter)21fun String.httpPost(parameters: Parameters? = null): Request =22 Fuel.post(this, parameters)23fun RequestFactory.PathStringConvertible.httpPost(parameters: Parameters? = null): Request =24 this.path.httpPost(parameters)25fun String.httpPut(parameters: Parameters? = null): Request =26 Fuel.put(this, parameters)27fun RequestFactory.PathStringConvertible.httpPut(parameter: Parameters? = null): Request =28 this.path.httpPut(parameter)29fun String.httpPatch(parameters: Parameters? = null): Request =30 Fuel.patch(this, parameters)31fun RequestFactory.PathStringConvertible.httpPatch(parameter: Parameters? = null): Request =32 this.path.httpPatch(parameter)33fun String.httpDelete(parameters: Parameters? = null): Request =34 Fuel.delete(this, parameters)35fun RequestFactory.PathStringConvertible.httpDelete(parameter: Parameters? = null): Request =36 this.path.httpDelete(parameter)37fun String.httpDownload(parameter: Parameters? = null, method: Method = Method.GET): DownloadRequest =38 Fuel.download(this, method, parameter)39fun RequestFactory.PathStringConvertible.httpDownload(parameters: Parameters? = null, method: Method = Method.GET): DownloadRequest =40 this.path.httpDownload(parameters, method)41fun String.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =42 Fuel.upload(this, method, parameters)43fun RequestFactory.PathStringConvertible.httpUpload(parameters: Parameters? = null, method: Method = Method.POST): UploadRequest =44 this.path.httpUpload(parameters, method)45fun String.httpHead(parameters: Parameters? = null): Request =46 Fuel.head(this, parameters)47fun RequestFactory.PathStringConvertible.httpHead(parameters: Parameters? = null): Request =48 this.path.httpHead(parameters)...

Full Screen

Full Screen

FuelClient.kt

Source:FuelClient.kt Github

copy

Full Screen

1package org.imperial.mrc.hint.clients2import com.github.kittinunf.fuel.core.FileDataPart3import com.github.kittinunf.fuel.core.Parameters4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.httpGet6import com.github.kittinunf.fuel.httpPost7import com.github.kittinunf.fuel.httpUpload8import org.imperial.mrc.hint.asResponseEntity9import org.springframework.http.ResponseEntity10import java.io.File11abstract class FuelClient(protected val baseUrl: String)12{13 companion object14 {15 private const val TIMEOUT = 12000016 }17 abstract fun standardHeaders(): Map<String, Any>18 fun get(url: String): ResponseEntity<String>19 {20 return "$baseUrl/$url".httpGet()21 .header(standardHeaders())22 .addTimeouts()23 .response()24 .second25 .asResponseEntity()26 }27 fun post(url: String, params: List<Pair<String, String>>): ResponseEntity<String>28 {29 return "$baseUrl/$url".httpPost(params)30 .addTimeouts()31 .header(standardHeaders())32 .response()33 .second34 .asResponseEntity()35 }36 protected open fun postJson(urlPath: String?, json: String): ResponseEntity<String>37 {38 val url = if (urlPath === null)39 {40 baseUrl41 }42 else43 {44 "$baseUrl/$urlPath"45 }46 return url.httpPost()47 .addTimeouts()48 .header(standardHeaders())49 .header("Content-Type" to "application/json")50 .body(json)51 .response()52 .second53 .asResponseEntity()54 }55 protected fun postEmpty(url: String): ResponseEntity<String>56 {57 return "$baseUrl/$url".httpPost()58 .addTimeouts()59 .header(standardHeaders())60 .response()61 .second62 .asResponseEntity()63 }64 protected fun Request.addTimeouts(): Request65 {66 return this.timeout(TIMEOUT)67 .timeoutRead(TIMEOUT)68 }69 fun postFile(url: String, parameters: Parameters, file: Pair<String, File>): ResponseEntity<String>70 {71 return "$baseUrl/$url".httpUpload(parameters)72 .add(FileDataPart(file.second, file.first))73 .addTimeouts()74 .header(standardHeaders())75 .response()76 .second77 .asResponseEntity()78 }79}...

Full Screen

Full Screen

createAttachment.kt

Source:createAttachment.kt Github

copy

Full Screen

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 }37 } catch (e: Throwable) {38 Single.error<CreateAttachmentResponse>(ConfluenceException(it.error.exception.message ?: it.error.message ?: it.error.response.responseMessage))39 }40 }41 }42 }43}...

Full Screen

Full Screen

String.httpUpload

Using AI Code Generation

copy

Full Screen

1class MainActivity : AppCompatActivity() {2 override fun onCreate(savedInstanceState: Bundle?) {3 super.onCreate(savedInstanceState)4 setContentView(R.layout.activity_main)5 val file = File("path/to/file")6 val (request, response, result) = url.httpUpload()7 .file("file", file)8 .responseString()9 Log.d("MainActivity", "Response : ${result.component1()}")10 }11}12class MainActivity : AppCompatActivity() {13 override fun onCreate(savedInstanceState: Bundle?) {14 super.onCreate(savedInstanceState)15 setContentView(R.layout.activity_main)16 val file = File("path/to/file")17 val (request, response, result) = url.httpDownload()18 .destination { response, url ->19 }20 .progress { readBytes, totalBytes ->21 Log.d("MainActivity", "Downloaded $readBytes of $totalBytes")22 }23 .responseString()24 Log.d("MainActivity", "Response : ${result.component1()}")25 }26}27class MainActivity : AppCompatActivity() {28 override fun onCreate(savedInstanceState: Bundle?) {29 super.onCreate(savedInstanceState)30 setContentView(R.layout.activity_main)31 val file = File("path/to/file")32 val (request, response, result) = url.httpDownload()33 .destination { response, url ->34 }35 .progress { readBytes, totalBytes ->36 Log.d("MainActivity", "Downloaded $readBytes of $totalBytes")37 }38 .responseString()39 Log.d("MainActivity", "Response : ${result.component1()}")40 }41}42class MainActivity : AppCompatActivity() {43 override fun onCreate(savedInstanceState: Bundle?) {44 super.onCreate(savedInstanceState)45 setContentView(R.layout.activity_main)46 val (request, response, result) = url.httpGet()47 .responseString()48 Log.d("MainActivity", "Response : ${result.component1()}")49 }50}

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