Android OkHttp, 一行代码 OkHttp提升请求稳定性
时间:2019-10-15
本文章向大家介绍Android OkHttp, 一行代码 OkHttp提升请求稳定性,主要包括Android OkHttp, 一行代码 OkHttp提升请求稳定性使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
OkHttp是可以说是Android开发中,每个项目都必需依赖的网络库,我们可以很便捷高效的处理网络请求,极大的提升了编码效率。但是有时候,我们使用OkHttp也会遇到这样的问题
一.崩溃的stacktrace
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的内容介绍。
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
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中
fun createOKHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(SafeGuardInterceptor()) .build() }
当我们再次执行有NPE的代码,日志就发生了改变(不再是崩溃的日志,而是异常的日志)
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) W System.err: Caused by: java.lang.NullPointerException: blablabla W System.err: at com.example.okhttpexceptionsample.MainActivity$createNPEInterceptor$1.intercept(MainActivity.kt:61) 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 com.example.okhttpexceptionsample.SafeGuardInterceptor.intercept(SafeGuardInterceptor.kt:10) W System.err: ... 7 more
上述需要注意两点
- 添加的是Interceptor,而不是NetworkInterceptor
- 顺序很重要,一定要放在第一个位置
四.这么做有什么问题
这么做,当然可以明显增强请求的稳定性和应用的崩溃率。但是是不是也有一些问题呢?比如
- 将问题情况吞掉,不利于发现问题呢
确实可能存在上述的问题,但是我们可以利用下面的方式减轻或者解决问题 - 只针对release情况应用SafeGuardInterceptor,这样便于debug情况下更容易发现
- 针对不同的build variants进行配置,便于尽可能的小范围发现问题
- 实行更加智能的动态开启策略。
在软件工程中,很多决定都是trade-off的体现,具体的实施方案大家可以自行平衡选择。
关于我
更多Android高级面试合集放在github上面了,
需要的小伙伴可以点击关于我 联系我获取
非常希望和大家一起交流 , 共同进步
目前是一名程序员,不仅分享 Android开发相关知识,同时还分享技术人成长历程,包括个人总结,职场经验,面试经验等,希望能让你少走一点弯路。
原文地址:https://www.cnblogs.com/1157760522ch/p/11678208.html
- Django--admin源码流程
- Spring Security笔记:Remember Me(下次自动登录)
- day8、 显示Linux路由表、各列信息
- day9、用户登陆出现-bash-4.1$错误的原因及解决方法
- jboss eap 6.3 域(Domain)模式配置
- 揭穿数据分析的12个神话
- jboss eap 6.3 集群(cluster)配置
- Django中Q查询及Q()对象
- jboss eap 6.3 集群(cluster)-Session 复制(Replication)
- JSP中的Servlet及Filter
- Django ORM详解
- Web前端培训:怎样成长为一个优秀的Web 前端开发工程师?
- Git操作
- 人工智能做的肉,你想吃吗?
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法