OkHttp: avoid leaked connection warning

前端 未结 2 921
情话喂你
情话喂你 2021-02-03 20:12

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 res         


        
相关标签:
2条回答
  • 2021-02-03 20:26

    As mentioned in the other answers, you have to close the response. A slightly cleaner approach would be to declare the ResponseBody in the try block, so that it will be automatically closed.

    try(ResponseBody body = ....){
    ....
    }
    
    0 讨论(0)
  • 2021-02-03 20:28

    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;
    }
    

    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();
    }
    
    0 讨论(0)
提交回复
热议问题