Best Fuel code snippet using com.github.kittinunf.fuel.core.RequestFactory.upload
Request.kt
Source:Request.kt
...385 fun body(body: String, charset: Charset = Charsets.UTF_8): Request386 /**387 * Sets the body to the contents of a file.388 *389 * @note this does *NOT* make this a multipart upload. For that you can use the upload request. This function can be390 * used if you want to upload the single contents of a text based file as an inline body.391 *392 * @note when charset is not UTF-8, this forces the client to use chunked encoding, because file.length() gives the393 * length of the file in bytes without considering the charset. If the charset is to be considered, the file needs394 * to be read in its entirety which defeats the purpose of using a file.395 *396 * @param file [File] the file to write to the body397 * @param charset [Charset] the charset to write with398 * @return [Request] the request399 */400 fun body(file: File, charset: Charset = Charsets.UTF_8): Request401 /**402 * Sets the body to a defined [Body]403 *404 * @param body [Body] the body to assign...
FuelManager.kt
Source:FuelManager.kt
...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...
RequestSharedInstanceTest.kt
Source:RequestSharedInstanceTest.kt
...262 }263 @Test264 fun httpUploadWithProgressValidCase() {265 mock.chain(266 request = mock.request().withMethod(Method.POST.value).withPath("/Fuel/upload"),267 response = mock.reflect()268 )269 var read = -1L270 var total = -1L271 val (request, response, result) = Fuel.upload(mock.path("Fuel/upload"))272 .add {273 val dir = System.getProperty("user.dir")274 FileDataPart(File(dir, "src/test/assets/lorem_ipsum_long.tmp"))275 }276 .progress { readBytes, totalBytes ->277 read = readBytes278 total = totalBytes279 println("read: $read, total: $total")280 }281 .responseString()282 val (data, error) = result283 assertThat(request, notNullValue())284 assertThat(response, notNullValue())285 assertThat(error, nullValue())...
BlockingRequestTest.kt
Source:BlockingRequestTest.kt
...210 @Test211 fun httpUploadRequestWithParameters() {212 val httpRequest = mock.request()213 .withMethod(Method.POST.value)214 .withPath("/upload")215 mock.chain(request = httpRequest, response = mock.reflect())216 val path = File(System.getProperty("user.dir"), "/src/test/assets").resolve("lorem_ipsum_long.tmp").path217 val (request, response, data) =218 manager.upload(mock.path("upload"), parameters = listOf("foo" to "bar", "foo1" to "bar1"))219 .add { FileDataPart.from(path, "lorem_ipsum_long.tmp") }220 .responseString()221 assertThat(request, notNullValue())222 assertThat(response, notNullValue())223 assertThat(data.get(), notNullValue())224 val statusCode = HttpURLConnection.HTTP_OK225 assertThat(response.statusCode, equalTo(statusCode))226 }227}...
RequestFactory.kt
Source:RequestFactory.kt
...67 * @return [DownloadRequest] the request (extended for download)68 */69 fun download(convertible: PathStringConvertible, method: Method = Method.GET, parameters: Parameters? = null): DownloadRequest70 /**71 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can upload blobs and72 * Data Parts73 *74 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path75 * @param method [Method] the method to upload with, defaults to [Method.POST]76 * @param parameters [Parameters] the optional parameters77 * @return [UploadRequest] the request (extended for upload)78 */79 fun upload(convertible: PathStringConvertible, method: Method = Method.POST, parameters: Parameters? = null): UploadRequest80 /**81 * Create a [method] [Request] to [path] with [parameters], which can upload blobs and Data Parts82 *83 * @parameters path [String] the absolute or relative to [FuelManager.instance]' base-path path84 * @parameters method [Method] the method to upload with, defaults to [Method.POST]85 * @parameters parameters [Parameters] the optional parameters86 * @return [UploadRequest] the request (extended for upload)87 */88 fun upload(path: String, method: Method = Method.POST, parameters: Parameters? = null): UploadRequest89 /**90 * Create a [Method.GET] [Request] to [path] with [parameters]91 *92 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path93 * @param parameters [Parameters] the optional parameters94 * @return [Request] the request95 */96 fun get(path: String, parameters: Parameters? = null): Request97 /**98 * Create a [Method.GET] [Request] to [PathStringConvertible.path] with [parameters]99 *100 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path101 * @param parameters [Parameters] the optional parameters102 * @return [Request] the request...
RequestPathStringConvertibleExtensionTest.kt
Source:RequestPathStringConvertibleExtensionTest.kt
...113 }114 @Test115 fun httpUploadRequestWithSharedInstance() {116 mock.chain(117 request = mock.request().withMethod(Method.POST.value).withPath("/http-upload"),118 response = mock.reflect()119 )120 val (request, response, result) = PathStringConvertibleImpl(mock.path("http-upload"))121 .httpUpload()122 .add { FileDataPart.from(File(System.getProperty("user.dir"), "src/test/assets").absolutePath, "lorem_ipsum_long.tmp") }123 .responseString()124 val (data, error) = result125 assertThat(request, notNullValue())126 assertThat(response, notNullValue())127 assertThat(error, nullValue())128 assertThat(data, notNullValue())129 val statusCode = HttpURLConnection.HTTP_OK130 assertThat(response.statusCode, equalTo(statusCode))131 }132 @Test133 fun httpDownloadRequestWithSharedInstance() {134 mock.chain(...
Fuel.kt
Source:Fuel.kt
...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)...
upload
Using AI Code Generation
1val (request, response, result) = Fuel.upload("/upload").source { request, url ->2FileInputStream(File("path/to/file"))3}.response()4val (request, response, result) = Fuel.upload("/upload").apply {5source { request, url ->6FileInputStream(File("path/to/file"))7}8}.response()9val (request, response, result) = upload("/upload").apply {10source { request, url ->11FileInputStream(File("path/to/file"))12}13}.response()
upload
Using AI Code Generation
1 .add(filePart)2 .add(textPart)3 .responseString()4 println(request)5 println(response)6 println(result)7 .add(filePart)8 .add(textPart)9 .responseString()10 println(request2)11 println(response2)12 println(result2)13 .add(filePart)14 .add(textPart)15 .responseString()16 println(request3)17 println(response3)18 println(result3)19}
upload
Using AI Code Generation
1val (request, response, result) = Fuel.upload("/upload").source { request, url ->2val file = File(filePath)3val fileContent = file.readBytes()4val boundary = "Boundary-" + UUID.randomUUID().toString()5val contentType = "multipart/form-data; boundary=" + boundary6" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r7val contentLength = (header.length + fileContent.size + footer.length).toLong()8request.addHeader("Content-Length", contentLength.toString())9request.addHeader("Content-Type", contentType)10out.write(header.toByteArray())11out.write(fileContent)12out.write(footer.toByteArray())13}14val responseString = result.get()
upload
Using AI Code Generation
1 .source { request, url ->2 FileInputStream("C:\\Users\\Mihir\\Desktop\\Test\\test.txt")3 }4 .progress { readBytes, totalBytes ->5 println("readBytes: $readBytes, totalBytes: $totalBytes")6 }7 .response()8 println(request)9 println(response)10 println(result)11 }12 fun testDownload() {13 .fileDestination { response, url ->14 File("C:\\Users\\Mihir\\Desktop\\Test\\test.txt")15 }16 .progress { readBytes, totalBytes ->17 println("readBytes: $readBytes, totalBytes: $totalBytes")18 }19 .response()20 println(request)21 println(response)22 println(result)23 }24}25import org.springframework.boot.autoconfigure.SpringBootApplication26import org.springframework.boot.runApplication27import org.springframework.http.HttpStatus28import org.springframework.http.ResponseEntity29import org.springframework.stereotype.Controller30import org.springframework.web.bind.annotation.PostMapping31import org.springframework.web.bind.annotation.RequestPart32import org.springframework.web.bind.annotation.ResponseBody33import org.springframework.web.multipart.MultipartFile34import java.io.File35import java.io.FileOutputStream36fun main(args: Array<String>) {37 runApplication<DemoApplication>(*args)38}39class UploadController {40 @PostMapping("/upload")41 fun uploadFile(@RequestPart("file") file: MultipartFile): ResponseEntity<String> {42 val file = File("C:\\Users\\Mihir\\Desktop\\Test\\test.txt")43 val fileOutputStream = FileOutputStream(file)44 fileOutputStream.write(file.bytes)45 fileOutputStream.close()46 return ResponseEntity("File Uploaded Successfully", HttpStatus.OK)47 }48 @PostMapping("/download")49 fun downloadFile(): ResponseEntity<ByteArray> {50 val file = File("C:\\Users\\Mihir\\Desktop\\Test\\test.txt")51 return ResponseEntity(file.readBytes(), HttpStatus.OK)52 }53}
upload
Using AI Code Generation
1var data = File("path/to/file.txt").readBytes()2var bytes = ByteArray(1024)3var inputStream = ByteArrayInputStream(data)4var outputStream = ByteArrayOutputStream()5var bytesRead = inputStream.read(bytes, 0, bytes.size)6while (bytesRead != -1) {7outputStream.write(bytes, 0, bytesRead)8bytesRead = inputStream.read(bytes, 0, bytes.size)9}10request.source { outputStream.toByteArray() }11request.responseString { request, response, result ->12println(response)13println(result)14}15var data = File("path/to/file.txt").readBytes()16var bytes = ByteArray(1024)17var inputStream = ByteArrayInputStream(data)18var outputStream = ByteArrayOutputStream()19var bytesRead = inputStream.read(bytes, 0, bytes.size)20while (bytesRead != -1) {21outputStream.write(bytes, 0, bytesRead)22bytesRead = inputStream.read(bytes, 0, bytes.size)23}24request.source { outputStream.toByteArray() }25request.responseString { request, response, result ->26println(response)27println(result)28}29var data = File("path/to/file.txt").readBytes()30var bytes = ByteArray(1024)31var inputStream = ByteArrayInputStream(data)32var outputStream = ByteArrayOutputStream()33var bytesRead = inputStream.read(bytes, 0, bytes.size)34while (bytesRead != -1) {35outputStream.write(bytes, 0, bytesRead)36bytesRead = inputStream.read(bytes, 0, bytes.size)37}38println(response)39println(result)40}
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!!