java - OkHttp : 避免泄漏连接警告

我正在使用OKHTTP 3,并且不断收到泄漏的连接警告:

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块中显式关闭流,方法如下:

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

我的应用程序对网络进行了大量的使用,但是这种警告经常出现。我从来没有注意到由这个假定的泄漏引起的任何问题,但我仍然想知道我是否做错了什么以及做错了什么。
有人能解释一下吗?

最佳答案:

通过升级到okhtp3.7,Eclipse开始警告我潜在的资源泄漏。我发现我的问题在于我写的这个方法:

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()之前会引发异常,因此流将保持打开状态。
在响应失败的情况下添加显式关闭解决了问题。

if (!response.isSuccessful()) {
    boolean repeatRequest = handleHttpError(response);
    response.close();
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值