ktor下载文件流

ktor 1.x版本

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

ktor 2.x版本

//传入url字符串进行下载
suspend fun HttpClient.download(url: String, fileOutputStream: FileOutputStream) = withContext(Dispatchers.IO) {
    this@download.get(url).bodyAsChannel().toInputStream().copyTo(fileOutputStream)
}
posted @ 2021-08-20 19:09  SoClear  阅读(700)  评论(0编辑  收藏  举报