Retrofit Closing Response Body

2019-02-21 23:54发布

问题:

I've been getting this error:

 A connection to ****** was leaked. Did you forget to close a response body?

So I went on and close the responses I get.

response.body().close()

Problem is if the response.body() is already converted to a custom class, there's no close method available. Also I tried calling raw and gives me an exception:

fetchSomething.enqueue(new Callback<SomethingClass>() {
            @Override
            public void onResponse(Call<SomethingClass> call, Response<SomethingClass> response) {


                //Closes the response body
                response.raw().body().close(); //<--- gives illegalStateException

            }

            @Override
            public void onFailure(Call<SomethingClass> call, Throwable t) {

            }
        });

    }

How do I close it?

回答1:

As mentioned here you can do something like below

 ResponseBody body =  response.raw().body();
                if (response.isSuccessful()) {
                    return body.string(); // Closes automatically.
                } else {
                    body.close();
                    return null;
                }

or

ResponseBody body = response.raw().body();
try {
  ...
} finally {
 body.close();
}

Hope it will solve your issue.