java.lang.OutOfMemoryError使用okhttp3下载文件

3 篇文章 0 订阅
1 篇文章 0 订阅

问题:在点击详情页面里预览在线pdf时,先是下载,然后预览,对于小文件pdf(36M)可以正常下载,但是大文件(360M)就会下载崩溃,没法预览pdf文件


..........................................................略
java.lang.OutOfMemoryError: Failed to allocate a  xxx byte allocation with xxx free bytes and 364MB until OOM; failed due to fragmentation (required continguous free xxx bytes where largest contiguous free 0 bytes)
..........................................................略
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java)
//定位具体的报错位置
..........................................................略
..........................................................略

解决方案:原因是大文件下载到内存中用作日志导致OOM
两个思路:

第一种:直接注释掉日志,避免OOM

            
   val okHttpClient = OkHttpClient.Builder()
//.addInterceptor(headerInterceptor)
//.addInterceptor(ProgressInterceptor())
//.addInterceptor(logInterceptor)
  .readTimeout(READ_TIME_OUT.toLong(), TimeUnit.MILLISECONDS)
  .connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.MILLISECONDS)
  .writeTimeout(WRITE_TIME_OUT.toLong(), TimeUnit.SECONDS)
  .build()
            

第二种:使用正确API下载大文件

1:Retrofit中使用Streaming


@Streaming
@GET
fun download(@Url url: String?): Observable<ResponseBody>

2:不记录日志


val logInterceptor = HttpLoggingInterceptor()
logInterceptor.level = HttpLoggingInterceptor.Level.BODY

改

val logInterceptor = HttpLoggingInterceptor()
logInterceptor.level = HttpLoggingInterceptor.Level.NONE

以上为参考,第一种亲测可用,第二种还没测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值