StrictMode:在附加的堆栈跟踪中获取资源但从未释放

Ale*_*hin 7 android okhttp retrofit2 android-strictmode

有时我会得到这个 StrictMode 异常:

2019-01-28 14:18:23.073 4597-4615/my.app.package E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'end' not called
        at dalvik.system.CloseGuard.open(CloseGuard.java:223)
        at java.util.zip.Inflater.<init>(Inflater.java:106)
        at okio.GzipSource.<init>(GzipSource.java:62)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:103)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at my.app.package.api.network.SetJsonContentTypeHeaderInterceptor.intercept(SetJsonContentTypeHeaderInterceptor.kt:15)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
Run Code Online (Sandbox Code Playgroud)

异常代码中提到的属于我的应用程序的唯一部分是SetJsonContentTypeHeaderInterceptor

import okhttp3.Interceptor

internal class SetJsonContentTypeHeaderInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain) =
        chain.request()
            .let {
                it.newBuilder()
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json")
                    .build()
            }
            .let { chain.proceed(it) }!!

}
Run Code Online (Sandbox Code Playgroud)

应用程序中使用的库版本:

好的http:3.11.0

改造:2.4.0

其原因是什么以及如何解决?

Jef*_*man 0

如果您查看 的源代码BridgeInterceptor,它显然会创建 aGzipSource并且不会关闭它。GzipSource实现Source扩展Closeable. 我不清楚这实际上是否泄漏了任何资源。无论如何,如果您看到严格模式违规,则意味着问题已在终结器中解决。

这是 okhttp 3.12.1 和 okio 1.15.0。有很多新版本,所以这个问题可能会被修复。