• ktor下载文件流


    suspend fun main() {
        //腾讯网logo
        val url1 = "https://mat1.gtimg.com/pingjs/ext2020/qqindex2018/dist/img/qq_logo_2x.png"
        //百度logo
        val url2="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"
    
        HttpClient(CIO).use { httpClient ->
            //用第一种方式下载图片
            httpClient.download(url1, File("./1.jpg").outputStream())
    
            //用第二种方式下载图片
            val httpStatement: HttpStatement = httpClient.get(url2)
            val fileOutputStream=File("./2.jpg").outputStream()
            download(httpStatement, fileOutputStream)
        }
    }
    
    //传入url字符串进行下载
    suspend fun HttpClient.download(url: String, fileOutputStream: FileOutputStream) = withContext(Dispatchers.IO) {
        this@download.get<HttpStatement>(url).execute { httpResponse ->
            val channel: ByteReadChannel = httpResponse.receive()
            while (!channel.isClosedForRead) {
                val packet = channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong())
                fileOutputStream.writePacket(packet)
            }
        }
    }
    
    //利用ktor client下载文件 能够实现高度自定义的HttpStatement
    suspend fun download(httpStatement: HttpStatement, fileOutputStream: FileOutputStream) = withContext(Dispatchers.IO) {
        httpStatement.execute { httpResponse ->
            val channel: ByteReadChannel = httpResponse.receive()
            while (!channel.isClosedForRead) {
                val packet = channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong())
                fileOutputStream.writePacket(packet)
            }
        }
    }
    
    
  • 相关阅读:
    Kotlin之类属性延迟初始化
    Android 之ANR
    Android之Handler基础篇
    Android Handler进阶篇
    Android 进程与线程管理
    Android 启动模式LaunchMode详解(LaunchMode四种模式详解)
    Android 应用版本号配置修改
    Android ViewGroup
    Android app与Activity主题配置
    Android 本地序列化
  • 原文地址:https://www.cnblogs.com/soclear/p/15167898.html
Copyright © 2020-2023  润新知