Android OkHttp, the request line of code lifting stability OkHttp

OkHttp is arguably Android development, each project must rely on the network library, we can be very convenient and efficient processing network request, which greatly enhance the coding efficiency. But sometimes, we use OkHttp will encounter such a problem

A. Crash 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)

II. Why crash

From the above stacktrace, we can analyze that occurred NullPointerException. A crash has occurred.

Wait, I remember OkHttp deal with abnormal situations have it.

Ah, indeed, OkHttp there are cases to handle exceptions, such as the occurrence of abnormal calls onFailure. For example, the content of the following description 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)
}

Yes.

  • OkHttp only deal with the case of IOException,
  • NullPointerException is not a subclass of IOException

It has not been processed, a crash has occurred.

Then there is no solution, so that collapse does not occur, the user not to interfere with it? In fact, it is possible.

III. Use 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)

The above code, we will any Throwableturn into IOExceptionWrapper(IOException disguised), then added to the OkHttpClient

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

When we again have to perform NPE code, log on has changed (no longer crash log, but an exception log)

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

Two things to note above

  • Adding that the Interceptor, rather than NetworkInterceptor
  • The order is important, it must be placed in the first position

    IV. What problems do

    It does, of course, can significantly enhance stability and collapse of requesting application. But is not it also have some problems? such as

  • The problem swallowed situation is not conducive to identify problems do
    indeed above problems may exist, but we can use the following ways to alleviate or solve the problem
  • SafeGuardInterceptor case only applied for release, which facilitates easier to spot where the debug
  • Configured for different build variants, as much as possible to facilitate the discovery of small problems
  • Implement a more intelligent dynamic open strategy.

In software engineering, a lot of decisions are the trade-off reflects specific embodiments we can balance their own choice.

about me

More Android interview senior collection on github above the
need of small partners can click on my  link I get
very much like to share with everyone and common progress

Currently a programmer, Android developers not only to share knowledge, but also to share technical people grew up, including personal summary, experience in the workplace, interview experience, you want to make less go a little detour.

Guess you like

Origin blog.51cto.com/14541311/2442629