使用 okhttp 下载 mp3 文件会产生损坏的文件 [英] Downloading mp3 file with okhttp produces corrupt file
本文介绍了使用 okhttp 下载 mp3 文件会产生损坏的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 http 链接下载 mp3 文件并将文件保存到本地存储.我尝试过的所有代码都保存了一个损坏的文件,该文件的大小是应有的两倍.文件应该是 1,204,787保存的文件为 2,478,272
I am trying to download an mp3 file from an http link and save the file to local storage. All the code I have tried saves a corrupt file that is slightly twice as large as it should be. File should be 1,204,787 File saved is 2,478,272
我要下载的文件是:rise-stage.bioinf.unc.edu/cue_audio/sampleaudio.mp3 –
The file I am trying to download is: rise-stage.bioinf.unc.edu/cue_audio/sampleaudio.mp3 –
手动下载时播放正常.
fun downloadFilea(url:String , localFileName:String)
{
val request: Request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
println("error"+e.toString())
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
var uri = dataMgr.getLocalURI(localFileName)
var file = File(uri)
val body = response.body
val contentLength = body!!.contentLength()
val source = body.source()
val DOWNLOAD_CHUNK_SIZE:Long = 2048
val sink: BufferedSink = file.sink().buffer()
var totalRead: Long = 0
var read: Long = 0
while (source.read(sink.buffer(), DOWNLOAD_CHUNK_SIZE).also {
read = it
} != -1L) {
totalRead += read
val progress = (totalRead * 100 / contentLength).toInt()
}
sink.writeAll(source)
sink.flush()
sink.close()
Log.d(logTag, "downloaded file")
}
})
}
推荐答案
可能是下载站点坏了,尝试手动访问.
Maybe the download site is broken, try to visit it manually.
这篇关于使用 okhttp 下载 mp3 文件会产生损坏的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文