我正在使用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();
}
我的应用程序对网络进行了大量的使用,但是这个警告经常出现。我从来没有观察到由这个假定的泄漏引起的任何问题,但我仍然想知道我是否做错了什么。
有人能解释一下这件事吗?
发布于 2017-05-05 15:06:00
通过升级到OkHttp 3.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();
}
https://stackoverflow.com/questions/38380371
复制相似问题