Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.DownloadRequest.Request.download
FuelManager.kt
Source:FuelManager.kt
1package com.github.kittinunf.fuel.core2import com.github.kittinunf.fuel.core.Client.Hook3import com.github.kittinunf.fuel.core.RequestFactory.PathStringConvertible4import com.github.kittinunf.fuel.core.RequestFactory.RequestConvertible5import com.github.kittinunf.fuel.core.interceptors.ParameterEncoder6import 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 parameters315 * @return [Request] the request316 */317 override fun head(convertible: PathStringConvertible, parameters: Parameters?): Request =318 request(Method.HEAD, convertible, parameters)319 /**320 * Resets this FuelManager to a clean instance321 */322 fun reset(): FuelManager {323 val clean = FuelManager()324 client = clean.client325 proxy = clean.proxy326 basePath = clean.basePath327 timeoutInMillisecond = clean.timeoutInMillisecond328 timeoutReadInMillisecond = clean.timeoutReadInMillisecond329 baseHeaders = clean.baseHeaders330 baseParams = clean.baseParams331 keystore = clean.keystore332 socketFactory = clean.socketFactory333 hostnameVerifier = clean.hostnameVerifier334 executorService = clean.executorService335 requestInterceptors.apply {336 clear()337 addAll(clean.requestInterceptors)338 }339 responseInterceptors.apply {340 clear()341 addAll(clean.responseInterceptors)342 }343 callbackExecutor = clean.callbackExecutor344 return this345 }346}...
DownLoadAppService.kt
Source:DownLoadAppService.kt
1package com.stxx.wyhvisitorandroid.service2import android.app.Notification3import android.app.NotificationChannel4import android.app.NotificationManager5import android.app.Service6import android.content.Context7import android.content.Intent8import android.content.Intent.FLAG_ACTIVITY_NEW_TASK9import android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION10import android.net.*11import android.os.Build12import android.os.Environment.DIRECTORY_DOWNLOADS13import android.view.WindowManager14import android.widget.RemoteViews15import androidx.annotation.RequiresApi16import androidx.appcompat.app.AlertDialog17import androidx.core.app.NotificationCompat18import androidx.core.app.NotificationManagerCompat19import androidx.core.content.ContextCompat20import androidx.core.content.FileProvider21import com.gavindon.mvvm_lib.base.MVVMBaseApplication22import com.gavindon.mvvm_lib.net.RxScheduler23import com.gavindon.mvvm_lib.widgets.showToast24import com.github.kittinunf.fuel.Fuel25import com.github.kittinunf.fuel.core.requests.DownloadRequest26import com.github.kittinunf.fuel.core.requests.tryCancel27import com.github.kittinunf.fuel.rx.rxResponse28import com.orhanobut.logger.Logger29import com.stxx.wyhvisitorandroid.NOTIFY_ID_DOWNLOAD30import com.stxx.wyhvisitorandroid.R31import com.stxx.wyhvisitorandroid.fileProviderAuth32import io.reactivex.disposables.CompositeDisposable33import org.jetbrains.anko.runOnUiThread34import java.io.File35import kotlin.math.ceil36/**37 * description:ä¸è½½arç§æ®App38 * Created by liNan on 2020/7/8 08:4939 */40class DownLoadAppService : Service() {41 companion object {42 const val REQUEST_CANCEL = "request_cancel"43 }44 private lateinit var downloadFile: File45 private lateinit var downloadRequest: DownloadRequest46 //å建notificationåå¨8.0ä¹ä¸å建NotificationChannel使ç¨47 private val channelId = "com.stxx.wyh.download"48 private var dialogMessage = "æ¯å¦è¦ä¸è½½ARç§æ®apk?"49 //ä¸è½½å®ææ å¿50 private var downloadFinishFlag: Boolean? = null51 private val compositeDisposable = CompositeDisposable()52 private val connectivityManager: ConnectivityManager by lazy {53 getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager54 }55 private var networkCallback: ConnectivityManager.NetworkCallback? = null56 //å建éç¥æ ä¸è½½è¿åº¦æ ·å¼(æ ¹å¸å±åªè½ä½¿ç¨frameLayout linearLayout relativeLayout)57 private val customRemoteViews: RemoteViews by lazy {58 RemoteViews(59 MVVMBaseApplication.appContext.packageName,60 R.layout.notify_download_app61 )62 }63 private val notification: Notification by lazy {64 NotificationCompat.Builder(this, channelId)65 .setTicker("æ£å¨ä¸è½½ARç§æ®apk..", customRemoteViews)66 .setWhen(System.currentTimeMillis())67 .setSmallIcon(R.mipmap.ic_icon)68 .setStyle(NotificationCompat.DecoratedCustomViewStyle())69 .setCustomContentView(customRemoteViews)70 .setAutoCancel(true)71 .setOngoing(true)72 .setOnlyAlertOnce(true)73 .build()74 }75 private val notifyManager by lazy {76 NotificationManagerCompat.from(MVVMBaseApplication.appContext)77 }78 override fun onCreate() {79 super.onCreate()80 network()81 downloadFile = File(this.getExternalFilesDir(DIRECTORY_DOWNLOADS), "ar.apk")82 }83 private fun showDialog() {84 val builder =85 AlertDialog.Builder(MVVMBaseApplication.getCurActivity()!!, R.style.downloadDialog)86 .setTitle("ä¸è½½")87 .setMessage(dialogMessage)88 .setPositiveButton(R.string.confirm) { dialog, _ ->89 downLoadApp()90 showNotify()91 dialog.dismiss()92 }.setNegativeButton("åæ¶") { dialog, which ->93 dialog.dismiss()94 }95 val dialog = builder.create()96 /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {97 dialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)98 } else {99 dialog.window?.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)100 }*/101 dialog.setOnShowListener { dialogs ->102 val negativeButton =103 (dialogs as AlertDialog).getButton(AlertDialog.BUTTON_NEGATIVE)104 negativeButton.setTextColor(ContextCompat.getColor(this, R.color.light))105 }106 dialog.show()107 }108 override fun onBind(intent: Intent?) = null109 override fun onStartCommand(intent: Intent?, flags: Int, tartId: Int): Int {110 /**111 * 1.å¤ææ¯å¦å·²ç»æä¸è½½å¥½çapk112 * 2.å¤ææ¯å¦æ£å¨ä¸è½½113 */114 if (downloadFile.exists() && downloadFile.length() >= 36000000) {115 Logger.i("${downloadFile.length()}")116 installApp()117 } else {118 if (::downloadRequest.isInitialized) {119 if (downloadFinishFlag == true) {120 showDialog()121 } else {122 MVVMBaseApplication.appContext.showToast("æ£å¨ä¸è½½..")123 }124 } else {125 showDialog()126 }127 }128 return START_NOT_STICKY129 }130 private var lastUpdate = 0L131 private fun downLoadApp() {132 downloadRequest =133 Fuel.download("http://manage.wenyuriverpark.com:8082/apk/ar.apk")134 // æ建FileOutputStream对象,æ件ä¸åå¨ä¼èªå¨æ°å»º135 compositeDisposable.add(downloadRequest.fileDestination { _, _ ->136 downloadFile137 }.progress { readBytes, totalBytes ->138 if (totalBytes != -1L) {139 // allow 2 updates/second max - more than 10/second will be blocked140 if (System.currentTimeMillis() - lastUpdate > 600) {141 lastUpdate = System.currentTimeMillis()142 Logger.i("$readBytes/$totalBytes")143 val progress = readBytes.toFloat() / totalBytes.toFloat() * 100144 updateProgress(progress)145 downloadFinishFlag = false146 }147 } else {148 //æ件é误149 runOnUiThread {150 MVVMBaseApplication.appContext.showToast("æä»¶ç ´æï¼ï¼")151 }152 downloadFinishFlag = true153 }154 }.rxResponse()155 .compose(RxScheduler.applySingleScheduler())156 .subscribe({157 notifyManager.cancel(NOTIFY_ID_DOWNLOAD)158 installApp()159 downloadFinishFlag = true160 }, {161 Logger.i(it.message.toString())162 downloadFinishFlag = false163 })164 )165 }166 private fun updateProgress(progress: Float) {167 customRemoteViews.setProgressBar(168 R.id.notify_progress,169 100,170 ceil(progress).toInt(),171 false172 )173 customRemoteViews.setTextViewText(174 R.id.tvProgress,175 "${ceil(progress).toInt()}%"176 )177 notifyManager.notify(NOTIFY_ID_DOWNLOAD, notification)178 }179 private fun installApp() {180 if (downloadFile.isFile) {181 // éè¿Intentå®è£
APKæ件182 val intents = Intent(Intent.ACTION_INSTALL_PACKAGE)183 val uri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {184 intents.addFlags(FLAG_GRANT_READ_URI_PERMISSION)185 FileProvider.getUriForFile(this, fileProviderAuth, downloadFile)186 } else {187 Uri.fromFile(downloadFile)188 }189 grantUriPermission(packageName, uri, FLAG_GRANT_READ_URI_PERMISSION)190 intents.addFlags(FLAG_ACTIVITY_NEW_TASK)191 intents.setDataAndType(uri, "application/vnd.android.package-archive")192 startActivity(intents)193 }194 }195 private fun showNotify() {196 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {197 val notificationChannel =198 NotificationChannel(199 channelId,200 "download",201 NotificationManager.IMPORTANCE_DEFAULT202 )203 notifyManager.createNotificationChannel(notificationChannel)204 }205 notifyManager.notify(NOTIFY_ID_DOWNLOAD, notification)206 }207 private fun network() {208 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {209 networkCallback = object : ConnectivityManager.NetworkCallback() {210 override fun onCapabilitiesChanged(211 network: Network?,212 networkCapabilities: NetworkCapabilities213 ) {214 //å½ç½ç»æ¹åæ¶215 notifyManager.cancel(NOTIFY_ID_DOWNLOAD)216 if (::downloadRequest.isInitialized) {217 downloadRequest.tryCancel()218 }219 downloadFinishFlag = true220 network(networkCapabilities)221 }222 }223 connectivityManager.registerNetworkCallback(224 NetworkRequest.Builder().build(),225 networkCallback226 )227 val networkCapabilities =228 connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)229 network(networkCapabilities)230 }231 }232 @RequiresApi(Build.VERSION_CODES.M)233 private fun network(networkCapabilities: NetworkCapabilities) {234 val hasWifi =235 networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)236 val hasCellular =237 networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)238 //æ¥çæ¯å¦æç½(å¿
é¡»æwifiè¿æ¥æè
移å¨ç½ç»å¦åä¼æåºå¼å¸¸)239 val isValidated =240 networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)241 dialogMessage = if (hasWifi) {242 if (isValidated) {243 "æ¨å½åå¤äºWIFIç¶æä¸\næ¯å¦è¦ä¸è½½ARç§æ®apk?"244 } else {245 "æ¨å½åç½ç»ä¸å¯ç¨!\n请è¿æ¥ç½ç»ä¹åå¯ç»§ç»ä¸è½½ARç§æ®apk"246 }247 } else if (hasCellular) {248 if (isValidated) {249 "æ¨å½åæªè¿æ¥WIFI\næ¯å¦è¦ä¸è½½ARç§æ®apk?"250 } else {251 "æ¨å½åç½ç»ä¸å¯ç¨!\n请è¿æ¥ç½ç»ä¹åå¯ç»§ç»ä¸è½½ARç§æ®apk"252 }253 } else {254 "æ¨å½åç½ç»ä¸å¯ç¨!\n请è¿æ¥ç½ç»ä¹åå¯ç»§ç»ä¸è½½ARç§æ®apk"255 }256 }257 override fun onDestroy() {258 notifyManager.cancel(NOTIFY_ID_DOWNLOAD)259 compositeDisposable.clear()260 if (networkCallback != null) {261 connectivityManager.unregisterNetworkCallback(networkCallback)262 }263 stopSelf()264 }265}...
RequestFactory.kt
Source:RequestFactory.kt
1package com.github.kittinunf.fuel.core2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.requests.DownloadRequest4import com.github.kittinunf.fuel.core.requests.UploadRequest5interface RequestFactory {6 /**7 * Make a request using [method] to [convertible]'s path with [parameters]8 *9 * @see FuelManager.instance10 * @see RequestFactory(Method, String, Parameters?)11 *12 * @param method [Method] the HTTP method to make the request with13 * @param convertible [PathStringConvertible]14 * @param parameters [Parameters?] list of parameters15 *16 * @return [Request] the request17 */18 fun request(method: Method, convertible: PathStringConvertible, parameters: Parameters? = null): Request19 /**20 * Make a request using [method] to [path] with [parameters]21 *22 * @see FuelManager.instance23 * @see FuelManager.request24 *25 * @param method [Method] the HTTP method to make the request with26 * @param path [String] the absolute url or relative to [FuelManager.instance] basePath27 * @param parameters [Parameters?] list of parameters28 *29 * @return [Request] the request30 */31 fun request(method: Method, path: String, parameters: Parameters? = null): Request32 /**33 * Make a request using from [convertible]34 *35 * @param convertible [RequestConvertible] the instance that can be turned into a [Request]36 * @return [Request] the request37 */38 fun request(convertible: RequestConvertible): Request39 /**40 * Anything that is a [PathStringConvertible] can be used as [path] parameter with [Fuel]41 */42 interface PathStringConvertible {43 val path: String44 }45 /**46 * Anything that is [RequestConvertible] can be used as [request] with [Fuel.request]47 */48 interface RequestConvertible {49 val request: Request50 }51 interface Convenience : RequestFactory {52 /**53 * Create a [method] [Request] to [path] with [parameters], which can download to a file54 *55 * @parameters path [String] the absolute or relative to [FuelManager.instance]' base-path path56 * @parameters method [Method] the method to download with, defaults to [Method.GET]57 * @parameters parameters [Parameters] the optional parameters58 * @return [DownloadRequest] the request (extended for download)59 */60 fun download(path: String, method: Method = Method.GET, parameters: Parameters? = null): DownloadRequest61 /**62 * Create a [method] [Request] to [PathStringConvertible.path] with [parameters], which can download to a file63 *64 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path65 * @param method [Method] the method to download with, defaults to [Method.GET]66 * @param parameters [Parameters] the optional parameters67 * @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 request103 */104 fun get(convertible: PathStringConvertible, parameters: Parameters? = null): Request105 /**106 * Create a [Method.POST] [Request] to [path] with [parameters]107 *108 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path109 * @param parameters [Parameters] the optional parameters110 * @return [Request] the request111 */112 fun post(path: String, parameters: Parameters? = null): Request113 /**114 * Create a [Method.POST] [Request] to [PathStringConvertible.path] with [parameters]115 *116 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path117 * @param parameters [Parameters] the optional parameters118 * @return [Request] the request119 */120 fun post(convertible: PathStringConvertible, parameters: Parameters? = null): Request121 /**122 * Create a [Method.PUT] [Request] to [path] with [parameters]123 *124 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path125 * @param parameters [Parameters] the optional parameters126 * @return [Request] the request127 */128 fun put(path: String, parameters: Parameters? = null): Request129 /**130 * Create a [Method.PUT] [Request] to [PathStringConvertible.path] with [parameters]131 *132 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path133 * @param parameters [Parameters] the optional parameters134 * @return [Request] the request135 */136 fun put(convertible: PathStringConvertible, parameters: Parameters? = null): Request137 /**138 * Create a [Method.PATCH] [Request] to [path] with [parameters]139 *140 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path141 * @param parameters [Parameters] the optional parameters142 * @return [Request] the request143 */144 fun patch(path: String, parameters: Parameters? = null): Request145 /**146 * Create a [Method.PATCH] [Request] to [PathStringConvertible.path] with [parameters]147 *148 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path149 * @param parameters [Parameters] the optional parameters150 * @return [Request] the request151 */152 fun patch(convertible: PathStringConvertible, parameters: Parameters? = null): Request153 /**154 * Create a [Method.DELETE] [Request] to [path] with [parameters]155 *156 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path157 * @param parameters [Parameters] the optional parameters158 * @return [Request] the request159 */160 fun delete(path: String, parameters: Parameters? = null): Request161 /**162 * Create a [Method.DELETE] [Request] to [PathStringConvertible.path] with [parameters]163 *164 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path165 * @param parameters [Parameters] the optional parameters166 * @return [Request] the request167 */168 fun delete(convertible: PathStringConvertible, parameters: Parameters? = null): Request169 /**170 * Create a [Method.HEAD] [Request] to [path] with [parameters]171 *172 * @param path [String] the absolute or relative to [FuelManager.instance]' base-path path173 * @param parameters [Parameters] the optional parameters174 * @return [Request] the request175 */176 fun head(path: String, parameters: Parameters? = null): Request177 /**178 * Create a [Method.HEAD] [Request] to [PathStringConvertible.path] with [parameters]179 *180 * @param convertible [PathStringConvertible] the absolute or relative to [FuelManager.instance]' base-path path181 * @param parameters [Parameters] the optional parameters182 * @return [Request] the request183 */184 fun head(convertible: PathStringConvertible, parameters: Parameters? = null): Request185 }186}...
Extensions.kt
Source:Extensions.kt
1package org.imperial.mrc.hint2import com.fasterxml.jackson.databind.JsonNode3import com.fasterxml.jackson.databind.ObjectMapper4import com.github.kittinunf.fuel.core.Headers5import com.github.kittinunf.fuel.core.Parameters6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.Response8import com.github.kittinunf.fuel.core.requests.DownloadRequest9import org.apache.commons.logging.LogFactory10import org.apache.commons.logging.Log11import org.imperial.mrc.hint.exceptions.HintExceptionHandler12import org.imperial.mrc.hint.models.ErrorDetail13import org.imperial.mrc.hint.models.SuccessResponse14import org.imperial.mrc.hint.models.asResponseEntity15import org.springframework.http.HttpStatus16import org.springframework.http.MediaType17import org.springframework.http.ResponseEntity18import org.springframework.util.LinkedMultiValueMap19import org.springframework.util.MultiValueMap20import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody21import java.io.*22import java.security.DigestInputStream23import java.security.MessageDigest24import javax.xml.bind.DatatypeConverter25fun httpStatusFromCode(code: Int): HttpStatus26{27 val status = HttpStatus.resolve(code) ?: return HttpStatus.INTERNAL_SERVER_ERROR28 return if (status <= HttpStatus.NOT_FOUND)29 {30 status31 }32 else33 {34 HttpStatus.INTERNAL_SERVER_ERROR35 }36}37fun headersToMultiMap(headers: Headers): MultiValueMap<String, String>38{39 val result = LinkedMultiValueMap<String, String>()40 headers.entries.forEach {41 result.addAll(it.key, it.value.toList())42 }43 return result44}45@Suppress("UNCHECKED_CAST")46fun Response.asResponseEntity(logger: Log = LogFactory.getLog(HintExceptionHandler::class.java)): ResponseEntity<String>47{48 val httpStatus = httpStatusFromCode(this.statusCode)49 if (this.statusCode == -1)50 {51 return ErrorDetail(httpStatus, "No response returned. The request may have timed out.")52 .toResponseEntity<String>()53 }54 return try55 {56 val body = this.body().asString(MediaType.APPLICATION_JSON_UTF8_VALUE)57 val json = ObjectMapper().readTree(body)58 if (!json.has("status") && !json.has("success"))59 {60 if (!httpStatus.isError)61 {62 SuccessResponse(json).asResponseEntity()63 }64 else65 {66 val message = json.asText()67 logger.error(message)68 ErrorDetail(httpStatus, message).toResponseEntity<String>()69 }70 }71 else if (json.has("status"))72 {73 // this is a hintr response, so already conforms to our response schema74 ResponseEntity.status(httpStatus)75 .contentType(MediaType.APPLICATION_JSON)76 .body(body)77 }78 else79 {80 // this is an ADR response, so convert to our response schema81 formatADRResponse(json, logger)82 }83 }84 catch (e: IOException)85 {86 if (this.body().asString(null).contains("504 Gateway Time-out"))87 {88 //Special case of ADR Gateway Timeouts returning HTML responses which cannot be parsed as JSON89 val message = "ADR request timed out"90 logger.error(message)91 ErrorDetail(HttpStatus.GATEWAY_TIMEOUT, message)92 .toResponseEntity<String>()93 }94 else95 {96 logger.error(e.message)97 ErrorDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Could not parse response.")98 .toResponseEntity<String>()99 }100 }101}102@Suppress("UNCHECKED_CAST")103fun formatADRResponse(json: JsonNode, logger: Log): ResponseEntity<String>104{105 logger.info("Parsing ADR response")106 return if (json["success"].asBoolean())107 {108 logger.info("ADR request successful")109 SuccessResponse(json["result"])110 .asResponseEntity()111 }112 else113 {114 logger.error(json)115 // ckan API always returns a 200, even when the request errors,116 // so just return a 500 for every error response117 ErrorDetail(HttpStatus.INTERNAL_SERVER_ERROR,118 json["error"]["message"].asText(),119 "ADR_ERROR")120 .toResponseEntity<String>()121 }122}123fun Request.getStreamingResponseEntity(headRequest: (url: String, parameters: Parameters?) -> Request)124 : ResponseEntity<StreamingResponseBody>125{126 val responseBody = StreamingResponseBody { outputStream: OutputStream ->127 //return an empty input stream to the body - don't need to re-use it128 val returnEmptyInputStream: () -> InputStream = { ByteArrayInputStream(ByteArray(0)) }129 (this as DownloadRequest).streamDestination { _, _ -> Pair(outputStream, returnEmptyInputStream) }130 .response()131 }132 val headReq = headRequest(this.url.toString(), null)133 val response = headReq.response()134 .second135 val httpStatus = httpStatusFromCode(response.statusCode)136 val headers = headersToMultiMap(response.headers)137 return ResponseEntity(responseBody, headers, httpStatus)138}139fun File.md5sum(): String140{141 val md = MessageDigest.getInstance("MD5")142 FileInputStream(this).use { fis ->143 DigestInputStream(fis, md).use { dis ->144 dis.readBytes()145 }146 }147 return DatatypeConverter.printHexBinary(md.digest())148}...
DownloadRequest.kt
Source:DownloadRequest.kt
1package com.github.kittinunf.fuel.core.requests2import com.github.kittinunf.fuel.core.ProgressCallback3import com.github.kittinunf.fuel.core.Request4import com.github.kittinunf.fuel.core.Response5import java.io.File6import java.io.FileInputStream7import java.io.FileOutputStream8import java.io.InputStream9import java.io.OutputStream10import java.net.URL11typealias LegacyDestinationCallback = (Response, URL) -> File12typealias FileDestinationCallback = (Response, Request) -> File13typealias StreamDestinationCallback = (Response, Request) -> Pair<OutputStream, DestinationAsStreamCallback>14typealias DestinationAsStreamCallback = () -> InputStream15class DownloadRequest private constructor(private val wrapped: Request) : Request by wrapped {16 override val request: DownloadRequest = this17 override fun toString() = "Download[\n\r\t$wrapped\n\r]"18 private lateinit var destinationCallback: StreamDestinationCallback19 init {20 executionOptions += this::transformResponse21 }22 @Deprecated("Use fileDestination with (Request, Response) -> File")23 fun destination(destination: LegacyDestinationCallback) =24 fileDestination { response: Response, request: Request -> destination(response, request.url) }25 /**26 * Set the destination callback27 *28 * @note destination *MUST* be writable or this may or may not silently fail, dependent on the JVM/engine this is29 * called on. For example, Android silently fails and hangs if used an inaccessible temporary directory, which30 * is syntactically valid.31 *32 * @param destination [FileDestinationCallback] callback called with the [Response] and [Request]33 * @return [DownloadRequest] self34 */35 fun fileDestination(destination: FileDestinationCallback) =36 streamDestination { response: Response, request: Request ->37 destination(response, request).let { file -> Pair(FileOutputStream(file), { FileInputStream(file) }) }38 }39 /**40 * Set the destination callback41 *42 * @note with the current implementation, the stream will be CLOSED after the body has been written to it.43 *44 * @param destination [StreamDestinationCallback] callback called with the [Response] and [Request]45 * @return []46 */47 fun streamDestination(destination: StreamDestinationCallback): DownloadRequest {48 destinationCallback = destination49 return request50 }51 fun progress(progress: ProgressCallback) = responseProgress(progress)52 private fun transformResponse(request: Request, response: Response): Response {53 val (output, inputCallback) = this.destinationCallback(response, request)54 output.use { outputStream ->55 response.body.toStream().use { inputStream ->56 inputStream.copyTo(out = outputStream)57 }58 }59 // This allows the stream to be written to disk first and then return the written file.60 // We can not calculate the length here because inputCallback might not return the actual output as we write it.61 return response.copy(body = DefaultBody.from(inputCallback, null))62 }63 companion object {64 val FEATURE: String = DownloadRequest::class.java.canonicalName65 fun enableFor(request: Request) = request.enabledFeatures66 .getOrPut(FEATURE) { DownloadRequest(request) } as DownloadRequest67 }68}69fun Request.download(): DownloadRequest = DownloadRequest.enableFor(this)...
main.kt
Source:main.kt
1import com.github.kittinunf.fuel.Fuel2import com.github.kittinunf.fuel.core.requests.DownloadRequest3import io.github.typosquat_pd.*4import java.io.File5fun main(args: Array<String>) {6 download_and_expand("https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip")7 val lic = LibrariesIoClient()8 val download_list = lic.search_packages("grant")?.forEach {9 if(it.language == "Java") {10 // Case: Binary11 // TODO12 // - Download .jar13 // - unzip .jar14 // - find .class files15 // - javap -v target.class ( create disassembly file )16 // - extract comment out ( comment out is original code extracted by the assembler )17 // - extract URL & high entropy (obfuscation) string18 } else if(it.language == "python" || it.language == "PHP") {19 // Memo: In the case of Python & PHP, "LibrariesIO" may not provide a Download Url.20 // The Script language allows for easy string checking.21 // TODO ...22 } else if(it.language == "go") {23 // Memo: In the case of GO, "LibrariesIO" may not provide a Download Url.24 // TODO ...25 } else if(it.language == "ruby") {26 // TODO27 // - download gem file (from url)28 // - tar xvf {targetfile}.gem -C {unzip target directory}29 // - unzip "data.tar.gz"30 // - (The Script language allows for easy string checking.)31 } else if(it.language == "npm" || it.language == "typescript") {32 val splittedUrl = it.latest_download_url.split("/")33 val fileName = splittedUrl.get(splittedUrl.size)34 val dr: DownloadRequest = Fuel.download(it.latest_download_url)35 // TODO36 // - download library tgz file (from url)37 // - unzip "target-library.tgz"38 // - search `.js`, `.ts` files39 // - (The Script language allows for easy string checking.)40 } else if(it.language == "c#") {41 // TODO42 // - download nupkg file43 // - rename & unzip nupkg44 // - analyze binary file...?45 }46 }47}48// TODO Rename49fun download_and_expand(url: String) {50 print("start------------")51 val DOWNLOAD_DESTINATION = "/tmp/"52 val splittedUrl = url.split("/")53 val fullFileName = splittedUrl.get(splittedUrl.size - 1)54 val fileAndExtension = fullFileName.split(".", limit=2)55 val fileName = fileAndExtension[0]56 val fileExtension = fileAndExtension[1]57 Fuel.download(url).fileDestination { response, _ ->58// File( DOWNLOAD_DESTINATION, fullFileName)59 File.createTempFile(fileName, fileExtension)60 }61 val downloadedFilePath = DOWNLOAD_DESTINATION + fullFileName62 print("end ------------")63 print(downloadedFilePath)64 print("end ------------")65}...
Fuel.kt
Source:Fuel.kt
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)...
DataFetchService.kt
Source:DataFetchService.kt
1package ro.hibyte.horus.service2import com.github.kittinunf.fuel.core.ResponseResultOf3import com.github.kittinunf.fuel.core.requests.DownloadRequest4import com.github.kittinunf.fuel.core.requests.download5import ro.hibyte.horus.api.JobModelEntity6import java.util.concurrent.TimeoutException7import javax.enterprise.context.Dependent8import javax.inject.Inject9import kotlin.jvm.Throws10@Dependent11class DataFetchService {12 @Inject13 private lateinit var reqestService: RequestService14 fun startJob(jsonBody: String): String {15 return reqestService.postt("datarequest", jsonBody)16 .responseObject(JobModelEntity.JobCreationResponse.Deserializer())17 .third.get().jobId18 }19 @Throws(TimeoutException::class)20 fun getJobStatus(jobId: String): String {21 var tries= 022 while (tries<1000){23 tries++24 val status = reqestService.gett("datarequest/status/$jobId")25 .responseObject(JobModelEntity.JobStatusResponse.Deserializer())26 .third.get().status27 when(status){28 "completed", "failed" -> return status29 }30 Thread.sleep(1000)31 }32 throw TimeoutException()33 }34 fun getJobResult(jobId: String): List<JobModelEntity.JobResultResponsContent> {35 return reqestService.gett("datarequest/jobs/$jobId/result")36 .responseObject(JobModelEntity.JobResultRespons.Deserializer())37 .third.get().content38 }39 fun createOrder(jobId: String, uri: String): ResponseResultOf<JobModelEntity.OrderCreateResponse> {40 val jsonOrder: String = "{\n" +41 " \"jobId\": \"$jobId\",\n" +42 " \"uri\": \"$uri\"\n" +43 "}"44 return reqestService.postt("dataorder", jsonOrder)45 .responseObject(JobModelEntity.OrderCreateResponse.Deserializer())46 }47 fun downloadResult(orderId: String): DownloadRequest {48 return reqestService.gett("dataorder/download/$orderId").download()49 }50}...
Request.download
Using AI Code Generation
1downloadRequest.progress { readBytes, totalBytes ->2println("Downloaded $readBytes bytes.")3}4downloadRequest.response { result ->5}6downloadRequest.progress { readBytes, totalBytes ->7println("Downloaded $readBytes bytes.")8}9downloadRequest.response { result ->10}11downloadRequest.progress { readBytes, totalBytes ->12println("Downloaded $readBytes bytes.")13}14downloadRequest.response { result ->15}16downloadRequest.progress { readBytes, totalBytes ->17println("Downloaded $readBytes bytes.")18}19downloadRequest.response { result ->20}21downloadRequest.progress { readBytes, totalBytes ->22println("Downloaded $readBytes bytes.")23}24downloadRequest.response { result ->25}26downloadRequest.progress { readBytes, totalBytes ->
Request.download
Using AI Code Generation
1val request = FuelManager.instance.download("/download")2request.destination { response, url ->3 val file = File.createTempFile("download", ".tmp")4 file.deleteOnExit()5}6val (data, error) = request.response()7println(data)8println(error)9val (data, error) = FuelManager.instance.download("/download").destination { response, url ->10 val file = File.createTempFile("download", ".tmp")11 file.deleteOnExit()12}.response()13println(data)14println(error)15val (data, error) = FuelManager.instance.download("/download").destination { response, url ->16 val file = File.createTempFile("download", ".tmp")17 file.deleteOnExit()18}.response()19println(data)20println(error)21val (data, error) = FuelManager.instance.download("/download").destination { response, url ->22 val file = File.createTempFile("download", ".tmp")23 file.deleteOnExit()24}.response()25println(data)26println(error)27val (data, error) = FuelManager.instance.download("/download").destination { response, url ->28 val file = File.createTempFile("download", ".tmp")29 file.deleteOnExit()30}.response()31println(data)32println(error)33val (data, error) = FuelManager.instance.download("/download").destination { response, url ->34 val file = File.createTempFile("download", ".tmp")
Request.download
Using AI Code Generation
1val (data, error) = result2data?.let {3val file = File("C:\\Users\\user\\Desktop\\test.png")4val downloadRequest = request.download(file)5downloadRequest.progress { readBytes, totalBytes ->6println("readBytes: $readBytes")7println("totalBytes: $totalBytes")8}9downloadRequest.response { request, response, result ->10val (data, error) = result11data?.let {12println("Downloaded to ${file.absolutePath}")13}14error?.let {15println("Error: ${it.message}")16}17}18}19error?.let {20println("Error: ${it.message}")21}22}23val (data, error) = result24data?.let {25val file = File("C:\\Users\\user\\Desktop\\test.png")26val downloadRequest = request.download(file)27downloadRequest.progress { readBytes, totalBytes ->28println("readBytes: $readBytes")29println("totalBytes: $totalBytes")30}31downloadRequest.response { request, response, result ->32val (data, error) = result33data?.let {34println("Downloaded to ${file.absolutePath}")35}36error?.let {37println("Error: ${it.message}")38}39}40}41error?.let {42println("Error: ${it.message}")43}44}45val (data, error) = result46data?.let {47val file = File("C:\\Users\\user\\Desktop\\test.png")48val downloadRequest = request.download(file)49downloadRequest.progress { readBytes, totalBytes ->50println("readBytes: $readBytes")51println("totalBytes: $totalBytes")52}53downloadRequest.response { request, response, result ->54val (data, error) = result55data?.let {56println("Downloaded to ${file.absolutePath}")57}58error?.let {59println("Error: ${it.message}")60}61}62}
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!!