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

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

FuelManager.kt

Source:FuelManager.kt Github

copy

Full Screen

...6import com.github.kittinunf.fuel.core.interceptors.redirectResponseInterceptor7import com.github.kittinunf.fuel.core.requests.DownloadRequest8import com.github.kittinunf.fuel.core.requests.UploadRequest9import com.github.kittinunf.fuel.core.requests.download10import com.github.kittinunf.fuel.core.requests.upload11import com.github.kittinunf.fuel.toolbox.HttpClient12import com.github.kittinunf.fuel.util.readWriteLazy13import java.net.Proxy14import java.security.KeyStore15import java.util.concurrent.Executor16import java.util.concurrent.ExecutorService17import java.util.concurrent.Executors18import javax.net.ssl.HostnameVerifier19import javax.net.ssl.HttpsURLConnection20import javax.net.ssl.SSLContext21import javax.net.ssl.SSLSocketFactory22import javax.net.ssl.TrustManagerFactory23typealias FoldableRequestInterceptor = (RequestTransformer) -> RequestTransformer24typealias FoldableResponseInterceptor = (ResponseTransformer) -> ResponseTransformer25class FuelManager : RequestFactory, RequestFactory.Convenience {26 var client: Client by readWriteLazy { HttpClient(proxy, hook = hook) }27 var proxy: Proxy? = null28 var basePath: String? = null29 var timeoutInMillisecond: Int = 15_00030 var timeoutReadInMillisecond: Int = timeoutInMillisecond31 var progressBufferSize: Int = DEFAULT_BUFFER_SIZE32 var hook: Hook = DefaultHook()33 var baseHeaders: Map<String, String>? = null34 var baseParams: Parameters = emptyList()35 var keystore: KeyStore? = null36 var socketFactory: SSLSocketFactory by readWriteLazy {37 keystore?.let {38 val trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())39 trustFactory.init(it)40 val sslContext = SSLContext.getInstance("SSL")41 sslContext.init(null, trustFactory.trustManagers, null)42 sslContext.socketFactory43 } ?: HttpsURLConnection.getDefaultSSLSocketFactory()44 }45 var hostnameVerifier: HostnameVerifier by readWriteLazy {46 HttpsURLConnection.getDefaultHostnameVerifier()47 }48 // background executionOptions49 var executorService: ExecutorService by readWriteLazy {50 Executors.newCachedThreadPool { command ->51 Thread(command).also { thread ->52 thread.priority = Thread.NORM_PRIORITY53 thread.isDaemon = true54 }55 }56 }57 private val requestInterceptors: MutableList<FoldableRequestInterceptor> =58 mutableListOf(ParameterEncoder)59 private val responseInterceptors: MutableList<FoldableResponseInterceptor> =60 mutableListOf(redirectResponseInterceptor(this))61 // callback executionOptions62 var callbackExecutor: Executor by readWriteLazy { createEnvironment().callbackExecutor }63 var forceMethods: Boolean = false64 /**65 * Make a request using [method] to [path] with [parameters]66 *67 * @see FuelManager.instance68 * @see FuelManager.applyOptions69 *70 * @param method [Method] the HTTP method to make the request with71 * @param path [String] the absolute url or relative to [FuelManager.instance] basePath72 * @param parameters [Parameters?] list of parameters73 *74 * @return [Request] the request75 */76 override fun request(method: Method, path: String, parameters: Parameters?): Request {77 val request = request(Encoding(78 httpMethod = method,79 urlString = path,80 baseUrlString = basePath,81 parameters = if (parameters == null) baseParams else baseParams + parameters82 ).request)83 return applyOptions(request)84 }85 /**86 * Make a request using [method] to [convertible]'s path with [parameters]87 *88 * @see FuelManager.instance89 * @see RequestFactory(Method, String, Parameters?)90 *91 * @param method [Method] the HTTP method to make the request with92 * @param convertible [PathStringConvertible]93 * @param parameters [Parameters?] list of parameters94 *95 * @return [Request] the request96 */97 override fun request(method: Method, convertible: PathStringConvertible, parameters: Parameters?): Request =98 request(method, convertible.path, parameters)99 /**100 * Make a request using from [convertible]101 *102 * @param convertible [RequestConvertible] the instance that can be turned into a [Request]103 * @return [Request] the request104 */105 override fun request(convertible: RequestConvertible): Request = applyOptions(convertible.request)106 /**107 * Create a [method] [Request] to [path] with [parameters], which can download to a file108 *109 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path110 * @param method [Method] the method to download with, defaults to [Method.GET]111 * @param parameters [Parameters] the optional parameters112 * @return [DownloadRequest] the request (extended for download)113 */114 override fun download(path: String, method: Method, parameters: Parameters?): DownloadRequest {115 val request = Encoding(116 httpMethod = method,117 urlString = path,118 baseUrlString = basePath,119 parameters = if (parameters == null) baseParams else baseParams + parameters120 ).request121 return applyOptions(request).download()122 }123 /**124 * Create a [method] [Request] to [path] with [parameters], which can upload blobs and Data Parts125 *126 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path127 * @param method [Method] the method to upload with, defaults to [Method.POST]128 * @param parameters [Parameters] the optional parameters129 * @return [UploadRequest] the request (extended for upload)130 */131 override fun upload(path: String, method: Method, parameters: Parameters?): UploadRequest {132 val request = Encoding(133 httpMethod = method,134 urlString = path,135 baseUrlString = basePath,136 parameters = if (parameters == null) baseParams else baseParams + parameters137 ).request138 return applyOptions(request).upload()139 }140 fun addRequestInterceptor(interceptor: FoldableRequestInterceptor): FuelManager {141 requestInterceptors += interceptor142 return this143 }144 fun addResponseInterceptor(interceptor: FoldableResponseInterceptor): FuelManager {145 responseInterceptors += interceptor146 return this147 }148 fun removeRequestInterceptor(interceptor: FoldableRequestInterceptor): FuelManager {149 requestInterceptors -= interceptor150 return this151 }152 fun removeResponseInterceptor(interceptor: FoldableResponseInterceptor): FuelManager {153 responseInterceptors -= interceptor154 return this155 }156 fun removeAllRequestInterceptors(): FuelManager {157 requestInterceptors.clear()158 return this159 }160 fun removeAllResponseInterceptors(): FuelManager {161 responseInterceptors.clear()162 return this163 }164 private fun applyOptions(request: Request): Request {165 // Sets base headers ONLY if they are not set166 val unsetBaseHeaders = request.headers.keys.fold(Headers.from(baseHeaders.orEmpty())) {167 result, it -> result.remove(it); result168 }169 return request.header(unsetBaseHeaders).apply {170 executionOptions = RequestExecutionOptions(171 client = client,172 socketFactory = socketFactory,173 hostnameVerifier = hostnameVerifier,174 callbackExecutor = callbackExecutor,175 requestTransformer = requestInterceptors.foldRight({ r: Request -> r }) { f, acc -> f(acc) },176 responseTransformer = responseInterceptors.foldRight({ _: Request, res: Response -> res }) { f, acc -> f(acc) },177 executorService = executorService178 ).also { executor ->179 executor.timeoutInMillisecond = timeoutInMillisecond180 executor.timeoutReadInMillisecond = timeoutReadInMillisecond181 executor.forceMethods = forceMethods182 }183 }184 }185 companion object {186 // manager187 var instance by readWriteLazy { FuelManager() }188 val progressBufferSize: Int get() = instance.progressBufferSize189 }190 /**191 * Create a [Method.GET] [Request] to [path] with [parameters]192 *193 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path194 * @param parameters [Parameters] the optional parameters195 * @return [Request] the request196 */197 override fun get(path: String, parameters: Parameters?): Request =198 request(Method.GET, path, parameters)199 /**200 * Create a [Method.GET] [Request] to [PathStringConvertible.path] with [parameters]201 *202 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path203 * @param parameters [Parameters] the optional parameters204 * @return [Request] the request205 */206 override fun get(convertible: PathStringConvertible, parameters: Parameters?): Request =207 request(Method.GET, convertible, parameters)208 /**209 * Create a [Method.POST] [Request] to [path] with [parameters]210 *211 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path212 * @param parameters [Parameters] the optional parameters213 * @return [Request] the request214 */215 override fun post(path: String, parameters: Parameters?): Request =216 request(Method.POST, path, parameters)217 /**218 * Create a [Method.POST] [Request] to [PathStringConvertible.path] with [parameters]219 *220 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path221 * @param parameters [Parameters] the optional parameters222 * @return [Request] the request223 */224 override fun post(convertible: PathStringConvertible, parameters: Parameters?): Request =225 request(Method.POST, convertible, parameters)226 /**227 * Create a [Method.PUT] [Request] to [path] with [parameters]228 *229 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path230 * @param parameters [Parameters] the optional parameters231 * @return [Request] the request232 */233 override fun put(path: String, parameters: Parameters?): Request =234 request(Method.PUT, path, parameters)235 /**236 * Create a [Method.PUT] [Request] to [PathStringConvertible.path] with [parameters]237 *238 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path239 * @param parameters [Parameters] the optional parameters240 * @return [Request] the request241 */242 override fun put(convertible: PathStringConvertible, parameters: Parameters?): Request =243 request(Method.PUT, convertible, parameters)244 /**245 * Create a [Method.PATCH] [Request] to [path] with [parameters]246 *247 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path248 * @param parameters [Parameters] the optional parameters249 * @return [Request] the request250 */251 override fun patch(path: String, parameters: Parameters?): Request =252 request(Method.PATCH, path, parameters)253 /**254 * Create a [Method.PATCH] [Request] to [PathStringConvertible.path] with [parameters]255 *256 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path257 * @param parameters [Parameters] the optional parameters258 * @return [Request] the request259 */260 override fun patch(convertible: PathStringConvertible, parameters: Parameters?): Request =261 request(Method.PATCH, convertible, parameters)262 /**263 * Create a [Method.DELETE] [Request] to [path] with [parameters]264 *265 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path266 * @param parameters [Parameters] the optional parameters267 * @return [Request] the request268 */269 override fun delete(path: String, parameters: Parameters?): Request =270 request(Method.DELETE, path, parameters)271 /**272 * Create a [Method.DELETE] [Request] to [PathStringConvertible.path] with [parameters]273 *274 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path275 * @param parameters [Parameters] the optional parameters276 * @return [Request] the request277 */278 override fun delete(convertible: PathStringConvertible, parameters: Parameters?): Request =279 request(Method.DELETE, convertible, parameters)280 /**281 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can download to a file282 *283 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path284 * @param method [Method] the method to download with, defaults to [Method.GET]285 * @param parameters [Parameters] the optional parameters286 * @return [DownloadRequest] the request (extended for download)287 */288 override fun download(convertible: PathStringConvertible, method: Method, parameters: Parameters?): DownloadRequest =289 download(convertible.path, method, parameters)290 /**291 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can upload blobs and292 * Data Parts293 *294 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path295 * @param method [Method] the method to upload with, defaults to [Method.POST]296 * @param parameters [Parameters] the optional parameters297 * @return [UploadRequest] the request (extended for upload)298 */299 override fun upload(convertible: PathStringConvertible, method: Method, parameters: Parameters?): UploadRequest =300 upload(convertible.path, method, parameters)301 /**302 * Create a [Method.HEAD] [Request] to [path] with [parameters]303 *304 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path305 * @param parameters [Parameters] the optional parameters306 * @return [Request] the request307 */308 override fun head(path: String, parameters: Parameters?): Request =309 request(Method.HEAD, path, parameters)310 /**311 * Create a [Method.HEAD] [Request] to [PathStringConvertible.path] with [parameters]312 *313 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path314 * @param parameters [Parameters] the optional parameters...

Full Screen

Full Screen

UploadRequestTest.kt

Source:UploadRequestTest.kt Github

copy

Full Screen

...87 assertThat("Name parameter is required", contentDisposition, containsString("name="))88 }89 }90 @Test91 fun uploadFileAsDataPart() {92 val manager = FuelManager()93 mock.chain(94 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),95 response = mock.reflect()96 )97 val file = File(currentDir, "lorem_ipsum_short.tmp")98 val triple = manager.upload(mock.path("upload"))99 .add(FileDataPart(file))100 .responseObject(MockReflected.Deserializer())101 assertFileUploaded(file, triple)102 }103 @Test104 fun uploadFileAndParameters() {105 val manager = FuelManager()106 mock.chain(107 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),108 response = mock.reflect()109 )110 val file = File(currentDir, "lorem_ipsum_short.tmp")111 val triple = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))112 .add(FileDataPart(file, name = "file"))113 .responseObject(MockReflected.Deserializer())114 val (request, _, result) = assertFileUploaded(file, triple, name = "file")115 assertThat(request.url.toExternalForm(), not(containsString("foo")))116 val (data, _) = result117 assertThat(data!!.body!!.string, containsString("name=\"foo\""))118 assertThat(data.body!!.string, containsString("bar"))119 }120 @Test121 fun uploadFileUsingPut() {122 val manager = FuelManager()123 mock.chain(124 request = mock.request().withMethod(Method.PUT.value).withPath("/upload"),125 response = mock.reflect()126 )127 val file = File(currentDir, "lorem_ipsum_long.tmp")128 val triple = manager.upload(mock.path("upload"), Method.PUT)129 .add(FileDataPart(file))130 .responseObject(MockReflected.Deserializer())131 assertFileUploaded(file, triple)132 }133 @Test134 fun uploadFileUsingProgress() {135 val manager = FuelManager()136 mock.chain(137 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),138 response = mock.reflect()139 )140 var read = -1L141 var total = -1L142 val file = File(currentDir, "lorem_ipsum_long.tmp")143 val triple = manager.upload(mock.path("upload"))144 .add(FileDataPart(file))145 .progress { readBytes, totalBytes -> read = readBytes; total = totalBytes }146 .responseObject(MockReflected.Deserializer())147 assertFileUploaded(file, triple)148 assertThat("Expected upload progress", read == total && read != -1L && total != -1L, equalTo(true))149 }150 @Test151 fun uploadToInvalidEndpoint() {152 val manager = FuelManager()153 mock.chain(154 request = mock.request().withMethod(Method.POST.value).withPath("/nope"),155 response = mock.response().withStatusCode(HttpURLConnection.HTTP_NOT_FOUND)156 )157 val (request, response, result) = manager.upload(mock.path("nope"))158 .add(FileDataPart(File(currentDir, "lorem_ipsum_short.tmp")))159 .responseString()160 val (data, error) = result161 assertThat("Expected request not to be null", request, notNullValue())162 assertThat("Expected response not to be null", response, notNullValue())163 assertThat("Expected error, actual data $data", error, notNullValue())164 val statusCode = HttpURLConnection.HTTP_NOT_FOUND165 assertThat(response.statusCode, equalTo(statusCode))166 }167 @Test168 fun uploadNonExistingFile() {169 val manager = FuelManager()170 mock.chain(171 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),172 response = mock.reflect()173 )174 val (request, response, result) = manager.upload(mock.path("upload"))175 .add { FileDataPart(File(currentDir, "not_found_file.tmp")) }176 .responseString()177 val (data, error) = result178 assertThat("Expected request not to be null", request, notNullValue())179 assertThat("Expected response not to be null", response, notNullValue())180 assertThat("Expected error, actual data $data", error, notNullValue())181 assertThat(error?.exception as FileNotFoundException, isA(FileNotFoundException::class.java))182 val statusCode = -1183 assertThat(response.statusCode, equalTo(statusCode))184 }185 @Test186 fun uploadMultipleFilesUnderSameField() {187 val manager = FuelManager()188 mock.chain(189 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),190 response = mock.reflect()191 )192 val shortFile = File(currentDir, "lorem_ipsum_short.tmp")193 val longFile = File(currentDir, "lorem_ipsum_long.tmp")194 val triple = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))195 .add(196 FileDataPart(shortFile, name = "file"),197 FileDataPart(longFile, name = "file")198 )199 .responseObject(MockReflected.Deserializer())200 assertFileUploaded(shortFile, triple, name = "file")201 assertFileUploaded(longFile, triple, name = "file")202 assertThat(triple.third.component1()!!.body!!.string, not(containsString("multipart/mixed")))203 }204 @Test205 fun uploadMultipleFilesUnderSameFieldArray() {206 val manager = FuelManager()207 mock.chain(208 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),209 response = mock.reflect()210 )211 val shortFile = File(currentDir, "lorem_ipsum_short.tmp")212 val longFile = File(currentDir, "lorem_ipsum_long.tmp")213 val triple = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))214 .add(215 FileDataPart(shortFile, name = "file[]"),216 FileDataPart(longFile, name = "file[]")217 )218 .responseObject(MockReflected.Deserializer())219 assertFileUploaded(shortFile, triple, name = "file[]")220 assertFileUploaded(longFile, triple, name = "file[]")221 assertThat(triple.third.component1()!!.body!!.string, not(containsString("multipart/mixed")))222 }223 @Test224 fun uploadMultipleFilesAsMultipleFields() {225 val manager = FuelManager()226 mock.chain(227 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),228 response = mock.reflect()229 )230 val shortFile = File(currentDir, "lorem_ipsum_short.tmp")231 val longFile = File(currentDir, "lorem_ipsum_long.tmp")232 val triple = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))233 .add(FileDataPart(shortFile, contentType = "image/jpeg"))234 .add(FileDataPart(longFile, name = "second-file", contentType = "image/jpeg"))235 .responseObject(MockReflected.Deserializer())236 assertFileUploaded(shortFile, triple)237 assertFileUploaded(longFile, triple, name = "second-file")238 }239 @Test240 fun uploadBlob() {241 val file = File(currentDir, "lorem_ipsum_short.tmp")242 val blob = BlobDataPart(file.inputStream(), contentLength = file.length(), filename = file.name, name = "coolblob")243 val manager = FuelManager()244 mock.chain(245 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),246 response = mock.reflect()247 )248 val triple = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))249 .add { blob }250 .responseObject(MockReflected.Deserializer())251 assertFileUploaded(file, triple, name = "coolblob", fileName = file.name)252 }253 @Test254 fun uploadWithCustomBoundary() {255 val manager = FuelManager()256 mock.chain(257 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),258 response = mock.reflect()259 )260 val boundary = "160f77ec3eff"261 val file = File(currentDir, "lorem_ipsum_short.tmp")262 val triple = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))263 .add(FileDataPart(file))264 .header(Headers.CONTENT_TYPE, "multipart/form-data; boundary=\"$boundary\"")265 .responseObject(MockReflected.Deserializer())266 val (_, _, result) = assertFileUploaded(file, triple)267 val (data, _) = result268 val body = data!!.body!!.string269 assertThat(body, containsString("--$boundary--"))270 }271 @Test272 fun uploadWithInvalidBoundary() {273 val manager = FuelManager()274 mock.chain(275 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),276 response = mock.reflect()277 )278 val (request, response, result) = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))279 .add(FileDataPart(File(currentDir, "lorem_ipsum_short.tmp")))280 .header(Headers.CONTENT_TYPE, "multipart/form-data")281 .responseObject(MockReflected.Deserializer())282 val (data, error) = result283 assertThat("Expected request not to be null", request, notNullValue())284 assertThat("Expected response not to be null", response, notNullValue())285 assertThat("Expected error, actual data $data", error, notNullValue())286 assertThat(error?.exception as? IllegalArgumentException, isA(IllegalArgumentException::class.java))287 }288 @Test289 fun uploadInlineDataPart() {290 val manager = FuelManager()291 mock.chain(292 request = mock.request().withMethod(Method.POST.value).withPath("/upload"),293 response = mock.reflect()294 )295 val shortFile = File(currentDir, "lorem_ipsum_short.tmp")296 val longFile = File(currentDir, "lorem_ipsum_long.tmp")297 val metadata = longFile.readText()298 val triple = manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar"))299 .add(300 FileDataPart(shortFile, name = "file"),301 InlineDataPart(metadata, name = "metadata", contentType = "application/json", filename = "metadata.json")302 )303 .responseObject(MockReflected.Deserializer())304 assertFileUploaded(shortFile, triple, name = "file")305 assertFileUploaded(longFile, triple, name = "metadata", fileName = "metadata.json")306 assertThat(triple.third.component1()!!.body!!.string, not(containsString("multipart/mixed")))307 }308}...

Full Screen

Full Screen

ServerApi.kt

Source:ServerApi.kt Github

copy

Full Screen

...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 }...

Full Screen

Full Screen

ServerManager.kt

Source:ServerManager.kt Github

copy

Full Screen

...43 deleteFormQueue(idOfTitleInQueue.get(i))44 }45 private fun getAccesTokenAndId() {46 val formData = listOf("type" to "email", "device_id" to "12345", "platform" to "android", "credentials" to "{\"email\":\"testingnetwork@gmail.com\",\"password\":\"tubitvtubitv\"}")47 val (request, response, result) = Fuel.upload("https://uapi.adrise.tv/user_device/login", parameters = formData).dataParts { request, url -> listOf<DataPart>() }.responseJson()48 result.fold(success = { json ->49 val token: String = json.obj().getString("access_token")50 val id : Int =json.obj().getInt("user_id")51 accesToken.add(0,token)52 idOfUser.add(0,id)53 }, failure = { error ->54 Assert.fail()55 })56 }57 private fun addToQueue(idOfTitle:Int){58 FuelManager.instance.baseHeaders= mapOf("Authorization" to accesToken.get(0))59 val url="https://uapi.adrise.tv/user_device/queues"60 val json=listOf("user_id" to idOfUser.get(0).toString(),"content_id" to idOfTitle,"content_type" to "movie")61 FuelManager.instance.baseHeaders= mapOf("Authorization" to accesToken.get(0))62 val (request, response, result)=Fuel.upload(url,parameters = json).dataParts{request, url -> listOf<DataPart>()}.responseJson()63 result.fold(success = {json ->64 val token :String=json.obj().getString("content_type")65 },failure = {66 error->Assert.fail()67 })68 }69 private fun deleteFormQueue(id:String){70 FuelManager.instance.baseHeaders= mapOf("Authorization" to accesToken.get(0))71 val url ="https://uapi.adrise.tv/user_device/queues/$id"72 val(request,response,result)=url.httpDelete().responseJson()73 result.fold(success = {},failure = {Assert.fail()})74 }75 private fun getQueueid(){76 FuelManager.instance.baseHeaders= mapOf("Authorization" to accesToken.get(0))...

Full Screen

Full Screen

Service.kt

Source:Service.kt Github

copy

Full Screen

...25 thread {26 val (_, response, _) = when (method) {27 Method.POST -> manager.post(url, params.toList())28 Method.GET -> manager.get(url, params.toList())29 Method.FORM -> manager.upload(url, POST).apply {30 if(params.isEmpty()) {31 for ((name, value) in formData)32 add(InlineDataPart(value.first, name, contentType = value.second))33 } else {34 parameters = params.toList()35 }36 }37 }.let {38 it.body(body?.jsonify() ?: return@let it)39 }.header(headers).let {40 it.appendHeader("Content-Type" to (contentType ?: return@let it))41 }.response()42 fn(response)43 }...

Full Screen

Full Screen

PublishModulesTask.kt

Source:PublishModulesTask.kt Github

copy

Full Screen

...43 .authentication().basic(terraformDsl.publisher.username!!, terraformDsl.publisher.secretKey!!)44 .body(it.readBytes())45 .responseString()46 if (response.second.statusCode != 201) {47 error("Error occurred during upload of $info. Artifactory returned status code ${response.second.statusCode}")48 }49 published = true50 println("Uploaded module $info")51 }52 }53 if (!published) {54 println("No modules were published")55 }56 }57 private fun checkIfExists(path: String, info: PackageInfo): Boolean {58 val getStatusCode = Fuel.get(path).response().second.statusCode59 if (getStatusCode != 200 && getStatusCode != 404) {60 error("Error occurred during get of $info. Artifactory returned status code $getStatusCode")61 }...

Full Screen

Full Screen

FileUploader.kt

Source:FileUploader.kt Github

copy

Full Screen

...23 basePath = baseUrl.toString()24 baseHeaders = mapOf("Content-Type" to "image/jpeg")25 }26 }27 open fun upload(file: File) {28 val dataSubject = PublishSubject.create<JSONObject>()29 for (dataObserver in dataObservers) {30 dataSubject.subscribe(dataObserver)31 }32 val progressSubject = PublishSubject.create<Int>()33 progressSubject.subscribe(progressObserver)34 doUpload(file, dataSubject, progressSubject)35 }36 private fun doUpload(file: File, dataSubject: PublishSubject<JSONObject>, progressSubject: PublishSubject<Int>): Unit {37 val fileSize = file.length()38 Fuel.upload("/model/predict")39 .add {40 FileDataPart(file, "image", "testimage.jpg")41 }42 .progress { writtenBytes, totalBytes ->43 val progress = writtenBytes.toFloat() / totalBytes.toFloat()44 Log.v(TAG, "Upload: ${progress}")45 progressSubject.onNext((100 * progress).toInt())46 }47 .also { Log.d(TAG, it.toString()) }48 .rxObject(AgeDeserializer)49 .subscribeOn(Schedulers.newThread())50 .observeOn(AndroidSchedulers.mainThread())51 .subscribe { result ->52 when (result) {...

Full Screen

Full Screen

Fuel.kt

Source:Fuel.kt Github

copy

Full Screen

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

upload

Using AI Code Generation

copy

Full Screen

1val (request, response, result) = Fuel.upload("/upload").source { request, url ->2 FileInputStream(File("test.jpg"))3}.responseString()4val (request, response, result) = Fuel.upload("/upload").source { request, url ->5 FileInputStream(File("test.jpg"))6}.responseString()7val (request, response, result) = Fuel.upload("/upload").source { request, url ->8 FileInputStream(File("test.jpg"))9}.responseString()10val (request, response, result) = Fuel.upload("/upload").source { request, url ->11 FileInputStream(File("test.jpg"))12}.responseString()13val (request, response, result) = Fuel.upload("/upload").source { request, url ->14 FileInputStream(File("test.jpg"))15}.responseString()16val (request, response, result) = Fuel.upload("/upload").source { request, url ->17 FileInputStream(File("test.jpg"))18}.responseString()19val (request, response, result) = Fuel.upload("/upload").source { request, url ->20 FileInputStream(File("test.jpg"))21}.responseString()22val (request, response, result) = Fuel.upload("/upload").source { request, url ->23 FileInputStream(File("test.jpg"))24}.responseString()25val (request, response, result) = Fuel.upload("/upload").source { request, url ->26 FileInputStream(File("test.jpg"))27}.responseString()28val (request, response, result) = Fuel.upload("/upload").source { request, url ->29 FileInputStream(File("test.jpg"))30}.responseString()

Full Screen

Full Screen

upload

Using AI Code Generation

copy

Full Screen

1Fuel.upload("/upload") { request ->2request.add(FileDataPart(File("path/to/file"), "file"))3}4Fuel.upload("/upload")5.add(FileDataPart(File("path/to/file"), "file"))6.responseString { request, response, result ->7}8Fuel.upload("/upload")9.add(FileDataPart(File("path/to/file"), "file"))10.progress { readBytes, totalBytes ->11}12.responseString { request, response, result ->13}14Fuel.upload("/upload")15.add(FileDataPart(File("path/to/file"), "file"))16.progress { readBytes, totalBytes ->17}18.responseString { request, response, result ->19}20Fuel.upload("/upload")21.add(FileDataPart(File("path/to/file"), "file"))22.progress { readBytes, totalBytes ->23}24.responseString { request, response, result ->25}26Fuel.upload("/upload")27.add(FileDataPart(File("path/to/file"), "file"))28.progress { readBytes, totalBytes ->29}30.responseString { request, response, result ->31}32Fuel.upload("/upload")33.add(FileDataPart(File("path/to/file"), "file"))34.progress { readBytes, totalBytes ->35}36.responseString { request, response, result ->37}

Full Screen

Full Screen

upload

Using AI Code Generation

copy

Full Screen

1@Throws(IOException::class)2fun uploadFileToServer() {3 val file = File("file_path")4 .add(file)5 .responseString()6 println(result)7}8@Throws(IOException::class)9fun uploadFileToServer() {10 val file = File("file_path")11 .add(file)12 .responseString()13 println(result)14}15@Throws(IOException::class)16fun uploadFileToServer() {17 val file = File("file_path")18 .add(file)19 .responseString()20 println(result)21}22@Throws(IOException::class)23fun uploadFileToServer() {24 val file = File("file_path")25 .add(file)26 .responseString()27 println(result)28}29@Throws(IOException::class)30fun uploadFileToServer() {31 val file = File("file_path")32 .add(file)33 .responseString()34 println(result)35}36@Throws(IOException::class)37fun uploadFileToServer() {38 val file = File("file_path")39 .add(file)40 .responseString()41 println(result)42}43@Throws(IOException::class)44fun uploadFileToServer() {45 val file = File("file_path")46 val (request, response, result) = Fuel.upload("http

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