OkHttp:避免泄漏连接警告 [英] OkHttp: avoid leaked connection warning

查看:116
本文介绍了OkHttp:避免泄漏连接警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 OkHttp 3,但我不断收到泄漏的连接警告:

I am using OkHttp 3, and I keep getting leaked connection warnings:

WARNING: A connection to https://help.helpling.com/ was leaked. Did you forget to close a response body?
Jul 14, 2016 6:57:09 PM okhttp3.ConnectionPool pruneAndGetAllocationCount

每次我得到一个 ResponseBody 时,我要么调用 .string(),它应该为我关闭流,或者我在 finally 中明确地关闭它 块,方式如下:

Everytime I get a ResponseBody, I either call .string() which supposedly closes the stream for me, or I explicitly close it in a finally block, in the following way:

ResponseBody responseBody = response.body();
try (Reader responseReader = responseBody.charStream()) {
    ...
}
finally {
    responseBody.close();
}

我的应用程序大量使用网络,但该警告经常出现.我从未观察到由这种假定的泄漏引起的任何问题,但我仍然想了解 if什么我做错了.

My application makes intense use of the network, and yet that warning appears frequently. I never observed any problem caused by this presumed leak, but I would still like to understand if and what I am doing wrong.

有人能解释一下吗?

推荐答案

通过升级到 OkHttp 3.7,Eclipse 开始警告我潜在的资源泄漏.我发现我的问题出在我写的这个方法中:

By upgrading to OkHttp 3.7, Eclipse started warning me of potential resource leaks. I found my problem to be in this method I wrote:

public static Response getResponse(HttpUrl url, OkHttpClient client) throws IOException {
    Builder request = new Request.Builder().url(url);
    Response response = client.newCall(request.build()).execute();
    if (!response.isSuccessful()) {
        boolean repeatRequest = handleHttpError(response);
        if (repeatRequest)
            return getResponse(url, client, etag);
        else
            throw new IOException(String.format("Cannot get successful response for url %s", url));
    }
    return response;
}

我假设总是调用 getResponse(url, client).body().string() 流会自动关闭.但是,只要响应不成功,就会在 .string() 执行之前引发异常,因此流将保持打开状态.

I assumed that by always calling getResponse(url, client).body().string() the stream would close automatically. But, whenever a response was unsuccessful, an exception would raise before the execution of .string(), thus the stream would remain open.

在响应失败的情况下添加显式关闭解决了问题.

Adding an explicit close in case of unsuccessful response solved the problem.

if (!response.isSuccessful()) {
    boolean repeatRequest = handleHttpError(response);
    response.close();
}

这篇关于OkHttp:避免泄漏连接警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆