Android 使用OkHttp 下载文件失败问题定位和修复

一、背景

使用Okhttp下载文件时,存在失败情况,刚开始以为是网络问题,后面添加相关日志发现,是在网络波动比较大的情况下,被判为timeout超时,结束了下载任务。

二、解决方案

有问题的下载配置写法:

Kotlin 复制代码
注:这里只是展示配置下载的关键代码
val client = OkHttpClient()
            val request = Request.Builder().url(downUrl).build()
            val response = client.newCall(request).execute()
            if (!response.isSuccessful) {
                callback.onFailure("Failed to download: ${response.code()}")
               // throw IOException("Failed to download: ${response.code()}")
            }

            response.body()?.use { body ->
                val inputStream = body.byteStream()
                val outputStream = FileOutputStream(file)
                val totalBytes = body.contentLength()
                var bytesDownloaded = 0L
                val buffer = ByteArray(4096)
                var bytesRead: Int
                var lastProgress = 0

                while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                    outputStream.write(buffer, 0, bytesRead)
                    bytesDownloaded += bytesRead
                    // 更新进度(确保回调到主线程)
                    val progress = (bytesDownloaded.toFloat() / totalBytes * 100f).toInt()

                    if (progress > lastProgress) {
                        lastProgress = progress
                        withContext(Dispatchers.Main) {
                            callback.onProgress(progress)
                        }
                    }

                    if(!isDownloading){
                        break
                    }
                }

优化修改后的写法:

通过EventListener中的callFailed可以打印相关日志,判断失败原因

Kotlin 复制代码
val client = OkHttpClient.Builder()
                .callTimeout(0, TimeUnit.SECONDS)//这里配置永不超时,也可以根据需要设置超时时间
                .connectTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
                .eventListener(object:EventListener() {
                     override fun callFailed (call: Call, ioe:IOException) {
                        // 记录失败日志
                        Log.d("AAAAA",">>>>>callFailed:${ioe.message},,cause:${ioe.cause}")
                         callback.onFailure("下载失败:${ioe.message}")
                     }
                })
                .build()


            val request = Request.Builder().url(downUrl).build()
            val response = client.newCall(request).execute()
            if (!response.isSuccessful) {
                callback.onFailure("Failed to download: ${response.code()}")
               // throw IOException("Failed to download: ${response.code()}")
            }

            response.body()?.use { body ->
                val inputStream = body.byteStream()
                val outputStream = FileOutputStream(file)
                val totalBytes = body.contentLength()
                var bytesDownloaded = 0L
                val buffer = ByteArray(4096)
                var bytesRead: Int
                var lastProgress = 0

                while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                    outputStream.write(buffer, 0, bytesRead)
                    bytesDownloaded += bytesRead
                    // 更新进度(确保回调到主线程)
                    val progress = (bytesDownloaded.toFloat() / totalBytes * 100f).toInt()

                    if (progress > lastProgress) {
                        lastProgress = progress
                        withContext(Dispatchers.Main) {
                            callback.onProgress(progress)
                        }
                    }

                    if(!isDownloading){
                        break
                    }
                }

OkHttp超时设置可以查阅这篇博客:

Android OkHttp 框架超时设置详解-CSDN博客

相关推荐
vistaup24 天前
OKHTTP 默认构建包含 android 4.4 的TLS 1.2 以及设备时间不对兼容
android·okhttp
bug-0071 个月前
关于前后端自动携带cookie跨域问题
okhttp
weixin_440784111 个月前
Java线程池工作原理浅析
android·java·开发语言·okhttp·android studio·android runtime
weixin_440784111 个月前
OkHttp使用指南
android·java·okhttp
闻哥1 个月前
从 AJAX 到浏览器渲染:前端底层原理与性能指标全解析
java·前端·spring boot·ajax·okhttp·面试
猿小羽1 个月前
OkHttp vs Retrofit 技术分析报告 - 1769404939594
http·okhttp·retrofit·csdn
AylKfTscDFw1 个月前
EtherCAT总线轴控制,大型非标组装检测设备成熟设备程序,注释非常详细,组合应用日本进口机...
okhttp
龙信科技1 个月前
【国内电子数据取证厂商龙信科技】Charles的简单介绍及基本配置
科技·okhttp
Filotimo_1 个月前
那在HTML中,action是什么
前端·okhttp·html
灵感菇_1 个月前
Android OkHttp框架全解析
android·java·okhttp·网络编程