您的位置:首页 > 房产 > 建筑 > 下载谷歌浏览器_广西建设网官网桂建云_百度app官方正式版_深圳seo培训

下载谷歌浏览器_广西建设网官网桂建云_百度app官方正式版_深圳seo培训

2025/7/5 4:41:39 来源:https://blog.csdn.net/banzhuantuqiang/article/details/148712248  浏览:    关键词:下载谷歌浏览器_广西建设网官网桂建云_百度app官方正式版_深圳seo培训
下载谷歌浏览器_广西建设网官网桂建云_百度app官方正式版_深圳seo培训

一、背景

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

二、解决方案

有问题的下载配置写法:

注:这里只是展示配置下载的关键代码
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 = 0Lval buffer = ByteArray(4096)var bytesRead: Intvar lastProgress = 0while (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 = progresswithContext(Dispatchers.Main) {callback.onProgress(progress)}}if(!isDownloading){break}}

优化修改后的写法:

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

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 = 0Lval buffer = ByteArray(4096)var bytesRead: Intvar lastProgress = 0while (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 = progresswithContext(Dispatchers.Main) {callback.onProgress(progress)}}if(!isDownloading){break}}

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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com