【问题标题】:How to download an .apk with ktor library and kotlin?如何使用 ktor 库和 kotlin 下载 .apk?
【发布时间】:2021-03-01 03:29:36
【问题描述】:

我正在使用 Ktor 库 (io.ktor:ktor-client-android:1.2.5) 下载文件。

当我下载图像时,一切都很好,但是当我想下载 .apk 时,它就不起作用了。

我正在使用ktor 1.2.5。

这是我使用的函数:

    suspend fun HttpClient.downloadFile(file: OutputStream, url: String): Flow<DownloadResult> {
    return flow {
        try {
            val response = call {
                url(url)
                method = HttpMethod.Get
            }.response
            val data = ByteArray(response.contentLength()!!.toInt())
            var offset = 0

            do {
                val currentRead = response.content.readAvailable(data, offset, data.size)
                offset += currentRead
                val progress = (offset * 100f / data.size).roundToInt()
                emit(DownloadResult.Progress(progress))
            } while (currentRead > 0)

            response.close()

            if (response.status.isSuccess()) {
                withContext(Dispatchers.IO) {
                    file.write(data)
                    //file.write()
                }
                emit(DownloadResult.Success)
            } else {
                emit(DownloadResult.Error("File not downloaded"))
            }
        } catch (e: TimeoutCancellationException) {
            emit(DownloadResult.Error("Connection timed out", e))
        } catch (t: Throwable) {
            emit(DownloadResult.Error("Failed to connect. ${t.message}"))
        }
    }
}

我是这样使用它的:

private fun downloadFile(view: View, context: Context, url: String, file: Uri) {
        val ktor = HttpClient(Android)

        //viewModel.setDownloading(true)
        context.contentResolver.openOutputStream(file)?.let { outputStream ->
            CoroutineScope(Dispatchers.IO).launch {
                ktor.downloadFile(outputStream, url).collect {
                    withContext(Dispatchers.Main) {
                        when (it) {
                            is DownloadResult.Success -> {
                                //viewModel.setDownloading(false)
                                view.custom_des_pb_progreso_descarga.progress = 0
                                Toast.makeText(context, "Descarga Completa", Toast.LENGTH_LONG).show()
                                dismiss()
                                viewFile(file, context)
                            }

                            is DownloadResult.Error -> {
                                Toast.makeText(context, "Error al descargar actualización. ${it.message}  ${it.cause} ", Toast.LENGTH_LONG).show()
                                dismiss()
                            }

                            is DownloadResult.Progress -> {
                                view.custom_des_pb_progreso_descarga.progress = it.progress
                                view.custom_des_pb_conteo_descarga.text = "${it.progress}%"
                            }
                        }
                    }
                }
            }
        }
    }

有人知道会发生什么吗?

【问题讨论】:

    标签: android kotlin download kotlin-coroutines ktor


    【解决方案1】:

    我建议从最简单的下载文件代码开始,然后在检查每一步时增加更多复杂性(流程和DownloadResult)。这是下载文件的工作代码:

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val client = HttpClient(Android)
    
            runBlocking {
                client.downloadFile(
                    "https://search.maven.org/remotecontent?filepath=de/sweetcode/e/1.7.2-alpha/e-1.7.2-alpha.jar",
                    applicationContext.openFileOutput("result.jar", MODE_PRIVATE)
                )
            }
        }
    }
    
    suspend fun HttpClient.downloadFile(url: String, output: OutputStream) {
        get<HttpStatement>(url).execute { response ->
            response.content.copyTo(output)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2022-11-03
      • 2019-08-13
      • 2017-03-28
      • 1970-01-01
      • 2017-01-28
      • 2014-04-07
      • 2020-02-23
      相关资源
      最近更新 更多