Skip to content

Commit

Permalink
1.将进度回调和断点续传的监听器拆分。
Browse files Browse the repository at this point in the history
2.优化下载逻辑,以支持那些不支持断点续传的服务器。
  • Loading branch information
xiazunyang committed Mar 24, 2022
1 parent 03bd8c4 commit 2785f60
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 14 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ buildscript {
maven("https://maven.aliyun.com/repository/jcenter")
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10")
classpath("com.github.dcendents:android-maven-gradle-plugin:2.1")
}
}
Expand Down
3 changes: 2 additions & 1 deletion http/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins {
}

group = "com.github.xiazunyang"
version = "1.0.2"
version = "1.0.3"

tasks.withType<KotlinCompile> {
kotlinOptions {
Expand All @@ -16,6 +16,7 @@ tasks.withType<KotlinCompile> {

dependencies {
implementation("com.j256.simplemagic:simplemagic:1.17")
compileOnly(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
compileOnly("com.squareup.retrofit2:retrofit:2.9.0")
compileOnly("com.squareup.okhttp3:okhttp:4.9.1")
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ class BreakpointResumeInterceptor : Interceptor {
var request = chain.request()
//取出文件参数
val fileOrDir = request.getTag<File>()
//取出下载进度回调参数
val dlProgressCallback = request.getTag<DlProgressCallback>()
//获取原请求
var response = chain.proceed(request)
if (fileOrDir == null) {
Expand Down Expand Up @@ -56,23 +54,19 @@ class BreakpointResumeInterceptor : Interceptor {
}
//如果文件已存在一部分,则重新发起请求,获取其余数据
if (existLength > 0) {
//获取剩余数据的请求体
request = request.newBuilder()
.removeHeader("range")
.addHeader("range", "bytes=${existLength}-")
.build()
//获取剩余数据的请求体
response.closeQuietly()
val rangeResponse = chain.proceed(request)
if(rangeResponse.code == 200) {
//如果服务器返回了剩余的部分数据,则关闭之前的响应
responseBody = response.body!!
} else {
//否则只能继续用原来的响应来写入
response = chain.proceed(request)
responseBody = response.body!!
if (responseBody.contentLength() == contentLength) {
// 如果剩余数据的大小与原大小相同,则说明服务器不支持Range参数,则忽略掉已存在的部分
responseBody.source().skip(existLength)
}
if (dlProgressCallback != null) {
//构建有进度回调的请求体
responseBody = ProgressResponseBody(responseBody, dlProgressCallback)
if (responseBody is ProgressResponseBody) {
//把已有的部分,算作已下载的进度,以处理正确的进度
responseBody.setExistLength(existLength)
}
Expand Down

0 comments on commit 2785f60

Please sign in to comment.