最近在做云备份功能。包含上传和下载。网上的断点上传太复杂了,不稳定,缺少重试机制等。我用最简单的方式交会你们
demo地址:
支持功能:
1.传入一个url。直接下载文件
2.下一次下载。可以进行断点
断点下载的原理
1.设置 header里面 添加range
2.响应的时候,服务器会一次返回流,不停的去取流。通过 RandomAccessFile
3.服务器返回的是本次文件的流,不包含之前的
4.返回码是206
断点下载思路
step 1:判断检查本地是否有下载文件,若存在,则获取已下载的文件大小 downloadLength,若不存在,那么本地已下载文件的长度为 0
step 2:获取将要下载的文件总大小(HTTP 响应头部的 content-Length)
step 3:比对已下载文件大小和将要下载的文件总大小(contentLength),判断要下载的长度
step 4:再即将发起下载请求的 HTTP 头部中添加即将下载的文件大小范围(Range: bytes = downloadLength - contentLength)
step 5 :封装okhttp2.响应之后,如何读出流
onResponse回调的参数是response,一般情况下,比如我们希望获得返回的字符串,可以通过response.body().string()获取;
如果希望获得返回的二进制字节数组,则调用response.body().bytes();
如果你想拿到返回的inputStream,则调用response.body().byteStream()
step 6:/** * HTTP请求是有一个Header的,里面有个Range属性是定义下载区域的,它接收的值是一个区间范围, * 比如:Range:bytes=0-10000。这样我们就可以按照一定的规则,将一个大文件拆分为若干很小的部分, * 然后分批次的下载,每个小块下载完成之后,再合并到文件中;这样即使下载中断了,重新下载时, * 也可以通过文件的字节长度来判断下载的起始点,然后重启断点续传的过程,直到最后完成下载过程。 */ Request request = new Request.Builder() .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength) //断点续传要用到的,指示下载的区间 .url(downloadUrl) .build();
源码:
fun syncDownLoad(ossListener: OssListener, transferItemModel: TransferItemModel) {//DownloadRequestUtil
if (this.mOssListener ==null) {
this.mOssListener = ossListener
}
d(TAG, "syncDownLoad:" + transferItemModel.name)
var file = File(MultiPartUtil.getDownloadPath(context) +"/" + transferItemModel.name)
if (raf ==null) {
raf = RandomAccessFile(file, "rwd")
}
if (!file.exists()) {
file.createNewFile()
}else {
val lengthRaf =raf?.length()
if (lengthRaf !=null) {
startPosition =lengthRaf
}
if (startPosition == transferItemModel.fileSize) {
file.delete()
startPosition =0
file.createNewFile()
raf = RandomAccessFile(file, "rwd")
}
}
raf?.seek(startPosition)
isCancle =false
d(TAG, "startPosition:" +startPosition)
this.transferItemModel = transferItemModel
var fileId = transferItemModel.fileId
var rangeStart =startPosition
var rangeEnd = transferItemModel.fileSize
val token = HttpRequestHelper.getToken()
var url = HttpPathEntity.HOST +"cloud/get_file?"
url = url +"fileId=" + fileId
url ="$url&token=$token"
d(TAG, "rangeStart=$rangeStart;rangeEnd=$rangeEnd")
val request = Request.Builder()
.addHeader("RANGE", "bytes=$rangeStart-$rangeEnd")//断点续传要用到的,指示下载的区间
.addHeader("token", token)//断点续传要用到的,指示下载的区间
.addHeader("timestamp", "" + System.currentTimeMillis())
.addHeader("deviceId", androidID)
.url(url)
.build()
call = ClouldOkClient.getInstance().okHttpClient!!.newCall(request)
call?.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e(TAG, "onFailure" + e.printStackTrace())
mOssListener?.onFailure(666, e.message)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val code = response.code()
d(TAG, "enqueue code:$code")
if (code ==DOWNLOAD_CODE) {
var inputStream: InputStream? =null
var responseBody = response.body()
inputStream = responseBody!!.byteStream()
val total = responseBody!!.contentLength()
d(TAG, " total:$total")
var len =0
val buf = ByteArray(2048)
val fileName = MultiPartUtil.getDownloadPath(context) +"/" + transferItemModel.name
val file = File(fileName)
if (!file.exists()) {
file.createNewFile()
}
var sum: Long =0
while (!isCancle &&inputStream.read(buf).also { len =it } != -1) {
raf?.write(buf, 0, len)
sum += len.toLong()
var currentPositon = sum +startPosition
var fileLength = total +startPosition
val progress = (currentPositon *1.0f / fileLength *100).toInt()
d(TAG, "当初写入的长度大小:" + len)
d(TAG, "read $progress" +"currentPositon:" + currentPositon +"sum:" + sum +"文件写入长度:" +raf?.length())
mOssListener?.onProgress(currentPositon, fileLength, progress)
}
val lengthRaf =raf?.length()
if (lengthRaf!! >= transferItemModel.fileSize) {
e(TAG, "下载完成了 lengthRaf:" + lengthRaf +"存放目录:" + fileName +"服务器总大小:" + transferItemModel.fileSize)
transferItemModel.fileDownloadTargetPath = file.path
raf?.close()
responseBody.close()
mOssListener?.onSuccess()
}else {
mOssListener?.onLoadCase(LoadStatus.STATE_PAUSE)
e(TAG, "暂停下载:")
}
}else if (code ==200) {
ossListener?.onSuccess()
e(TAG, "测试正常下载完成:")
}else {
ossListener?.onFailure(code, response.message())
e(TAG, "服务器异常:")
}
}
})
}