Android OkHttp, 一行代码 OkHttp提升请求稳定性

Android OkHttp, 一行代码 OkHttp提升请求稳定性,第1张

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

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.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 @R_502_2187@   * accepted the request before the failure.   */  fun onFailure(call: Call, e: IOException)  /**   * Called when the http response was successfully returned by the @R_502_2187@. 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.okhttpexceptionsampleimport okhttp3.Interceptorimport okhttp3.Responseimport 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.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开发相关知识,同时还分享技术人成长历程,包括个人总结,职场经验,面试经验等,希望能让你少走一点弯路。

总结

以上是内存溢出为你收集整理的Android OkHttp, 一行代码 OkHttp提升请求稳定性全部内容,希望文章能够帮你解决Android OkHttp, 一行代码 OkHttp提升请求稳定性所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1092847.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存