情境是這樣:
val url = "某個(gè)文件的下載地址"
val request = Request.Builder().get().url(url).build()
val okhttp = OkHttpClient()
val response = okhttp.newCall(request).execute()
println("content-length:${response.body?.contentLength()}")
打印的結(jié)果是"content-length:-1"
但是抓包發(fā)現(xiàn)response.header中content-length是有值的
那么為什么會(huì)出現(xiàn)這種情況呢?
分為以下兩種情況?
在沒(méi)有設(shè)置header "Accept-Encoding:gzip"的情況,okhttp 會(huì)自動(dòng)加上,這時(shí)候得到的reponse.body.contentLength() 是-1
response.body.byteStream() 得到的是okhttp 自動(dòng)幫我們解壓后的流在設(shè)置了"Accept-Encoding:gzip"的情況,okhttp不會(huì)再自動(dòng)添加"Accept-Encoding"header了,這時(shí)候得到的reponse.body.contentLength()是gzip 壓縮后的文件大小。
response.body.byteStream() 是需要使用GZipInputStream解壓縮的
那么為什么會(huì)這樣呢?
是因?yàn)閛khttp的原則是系統(tǒng)優(yōu)化網(wǎng)絡(luò),所以會(huì)默認(rèn)添加"Accept-Encoding:gzip",但是這個(gè)時(shí)候,response.header中的"content-length"返回的是壓縮后的文件大小,而response.body().byteStream() 是okhttp 幫我們gzip解壓之后流的,這個(gè)流的長(zhǎng)度和"content-length"返回的長(zhǎng)度是對(duì)不上的,因?yàn)橐粋€(gè)是壓縮前的文件大小,一個(gè)是壓縮后的文件大小,而壓縮前的文件大小之后讀取完畢之后才能知道,所以okhttp 中reponse.body.contentLength() 得到是-1,是在告訴我們它也不知道文件到底多大。
怎么解決呢?有兩種方法
- 設(shè)置 header 中的Accept-Encoding="",這樣即可得到正常的長(zhǎng)度,但是因?yàn)椴粏⒂胓zip所以下載速度會(huì)變慢
- 第二種,主動(dòng)設(shè)置"Accept-Encoding:gzip",并自己去處理gzip解壓的問(wèn)題
internal typealias DownloadProgress = (Int) -> Unit
private const val LOG_TAG = "PdfDownloader"
internal class PdfDownloader(
private val pdfDesc: PdfDesc,
private val okHttpClient: OkHttpClient,
private val downloadProgress: DownloadProgress
) {
private var progress: Int = 0
@WorkerThread
@Throws(IOException::class)
fun download(targetFile: File) {
val request = Request.Builder()
.get()
.addHeader("Accept-Encoding", "gzip")添加了就需要自己處理gzip了
.url(pdfDesc.uri.toString())
.build()
val response = okHttpClient.newCall(request).execute()
if (!response.isSuccessful) {
throw IOException("request fail,response code:${response.code}")
}
val body = response.body ?: throw IOException("empty body")
targetFile.parentFile?.mkdirs()
if (response.headers("content-encoding").contains("gzip")) {
// 服務(wù)器支持gzip,先下載到臨時(shí)文件中,再解壓
val tempFile = File(targetFile.parent, "${targetFile.name}.gzip").also {
it.delete()
it.deleteOnExit()
}
// 下載文件
using {
val netIS = body.byteStream().autoClose()
val tempOs = tempFile.outputStream().buffered().autoClose()
netIS.copyTo(body.contentLength(), tempOs)
}
// gzip 解壓
using {
val gzipIS = GZIPInputStream(tempFile.inputStream()).buffered().autoClose()
val targetOS = targetFile.outputStream().buffered().autoClose()
gzipIS.copyTo(targetOS)
}
tempFile.delete()
} else {
// 服務(wù)器不支持gzip,直接下載文件
using {
val netIS = body.byteStream().autoClose()
val tempOs = targetFile.outputStream().buffered().autoClose()
netIS.copyTo(body.contentLength(), tempOs)
}
}
}
private fun InputStream.copyTo(totalLength: Long, out: OutputStream): Long {
var bytesCopied: Long = 0
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = read(buffer)
while (bytes >= 0) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
if (totalLength > 0) {
val progress = (bytesCopied * 100 / totalLength).toInt()
if (progress != this@PdfDownloader.progress) {
this@PdfDownloader.progress = progress
Timber.tag(LOG_TAG).d("download progress:${progress}")
downloadProgress(progress)
}
}
bytes = read(buffer)
}
return bytesCopied
}
}
/*
* 以下代碼用來(lái)優(yōu)雅的關(guān)閉多個(gè)流
*/
internal fun <R> using(block: ResourceHolder.() -> R): R {
return ResourceHolder().use { it.block() }
}
internal class ResourceHolder : Closeable {
private val resources = arrayListOf<AutoCloseable>()
fun <T : AutoCloseable> T.autoClose(): T {
resources.add(this)
return this
}
override fun close() {
resources.reversed().forEach { it.close() }
}
}
希望遇到類(lèi)似問(wèn)題能幫到你,有問(wèn)題,請(qǐng)向我提問(wèn)。