Retrofit Closing Response Body

守給你的承諾、 提交于 2019-12-01 15:44:22

问题


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.



来源:https://stackoverflow.com/questions/39482514/retrofit-closing-response-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!