相关文章推荐
安静的匕首  ·  C语言中的popen()函数_popen可以 ...·  1 年前    · 
一直单身的手链  ·  带格式文本html ...·  2 年前    · 
爱热闹的竹笋  ·  批处理 隐藏cmd窗口的路径-掘金·  2 年前    · 
卖萌的充电器  ·  浅谈Notepad++选中行操作+快捷键+使 ...·  2 年前    · 
风流倜傥的佛珠  ·  LiveChart应用笔记-折线图 - 掘金·  2 年前    · 
Code  ›  一个小技巧提升 OkHttp 请求稳定性开发者社区
response
https://cloud.tencent.com/developer/article/1577716
坏坏的雪糕
2 年前
作者头像
技术小黑屋
0 篇文章

一个小技巧提升 OkHttp 请求稳定性

前往专栏
腾讯云
开发者社区
文档 意见反馈 控制台
首页
学习
活动
专区
工具
TVP
文章/答案/技术大牛
发布
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
社区首页 > 专栏 > 技术小黑屋 > 一个小技巧提升 OkHttp 请求稳定性

一个小技巧提升 OkHttp 请求稳定性

作者头像
技术小黑屋
发布 于 2020-01-19 19:03:48
1.6K 0
发布 于 2020-01-19 19:03:48
举报

OkHttp是可以说是Android开发中,每个项目都必需依赖的网络库,我们可以很便捷高效的处理网络请求,极大的提升了编码效率。但是有时候,我们使用OkHttp也会遇到这样的问题

崩溃的stacktrace

1 11

E AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher E AndroidRuntime: Process: com.example.okhttpexceptionsample, PID: 13564 E AndroidRuntime: java.lang.NullPointerException: blablabla E AndroidRuntime: at com.example.okhttpexceptionsample.MainActivity$createNPEInterceptor$1.intercept(MainActivity.kt:61) E AndroidRuntime: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112) E AndroidRuntime: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87) E AndroidRuntime: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184) E AndroidRuntime: at okhttp3.RealCall$AsyncCall.run(RealCall.kt:136) E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) E AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) E AndroidRuntime: at java.lang.Thread.run(Thread.java:784)

为什么会崩溃

从上面的stacktrace,我们可以分析到,发生了NullPointerException。发生了崩溃。

等等,我记得OkHttp有处理异常的情况呢。

嗯,确实,OkHttp有处理异常的情况,比如发生异常会调用 onFailure 。比如下面的Callback的内容介绍。

1 21

interface Callback { * Called when the request could not be executed due to cancellation, a connectivity problem or * timeout. Because networks can fail during an exchange, it is possible that the remote server * accepted the request before the failure. fun onFailure(call: Call, e: IOException) * Called when the HTTP response was successfully returned by the remote server. The callback may * proceed to read the response body with [Response.body]. The response is still live until its * response body is [closed][ResponseBody]. The recipient of the callback may consume the response * body on another thread. * Note that transport-layer success (receiving a HTTP response code, headers and body) does not * necessarily indicate application-layer success: `response` may still indicate an unhappy HTTP * response code like 404 or 500. @Throws(IOException::class) fun onResponse(call: Call, response: Response) }

是的,

  • OkHttp只处理了IOException的情况,
  • NullPointerException不是IOException的子类

所以没有被处理,发生了崩溃。

那么有没有办法解决,让这种崩溃不发生,对用户不进行干扰呢?其实是可以的。

使用Interceptor

1 23

package com.example.okhttpexceptionsample import okhttp3.Interceptor import okhttp3.Response import java.io.IOException * 对于Interceptor的intercept中可能出现的Throwable包裹成IOExceptionWrapper,转成网络请求失败,而不是应用崩溃 class SafeGuardInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { try { return chain.proceed(chain.request()) } catch (t: Throwable) { throw IOExceptionWrapper("SafeGuarded when requesting ${chain.request().url}", t) * 将chain.proceed处理中发生的Throwable包装成IOExceptionWrapper class IOExceptionWrapper(message: String?, cause: Throwable?) : IOException(message, cause)

上面的代码,我们将任何 Throwable 的转成 IOExceptionWrapper (伪装成IOException),然后添加到OkHttpClient中

1 5

fun createOKHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(SafeGuardInterceptor()) .build() }

当我们再次执行有NPE的代码,日志就发生了改变(不再是崩溃的日志,而是异常的日志)

1 15

W System.err: com.example.okhttpexceptionsample.IOExceptionWrapper: SafeGuarded=blablabla W System.err: at com.example.okhttpexceptionsample.SafeGuardInterceptor.intercept(SafeGuardInterceptor.kt:12) W System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112) W System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87) W System.err: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184) W System.err: at okhttp3.RealCall$AsyncCall.run(RealCall.kt:136) W System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) W System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) W System.err: at java.lang.Thread.run(Thread.java:784)

 
推荐文章
安静的匕首  ·  C语言中的popen()函数_popen可以用fclose关闭-CSDN博客
1 年前
一直单身的手链  ·  带格式文本html 直接复制粘贴,通过JS将带格式的文本复制到剪贴版的两种方法..._weixin_39997037的博客-CSDN博客
2 年前
爱热闹的竹笋  ·  批处理 隐藏cmd窗口的路径-掘金
2 年前
卖萌的充电器  ·  浅谈Notepad++选中行操作+快捷键+使用技巧【超详解】-阿里云开发者社区
2 年前
风流倜傥的佛珠  ·  LiveChart应用笔记-折线图 - 掘金
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号