改造关闭响应体 [英] Retrofit Closing Response Body

查看:80
本文介绍了改造关闭响应体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直收到此错误:

 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()

问题是,如果response.body()已转换为自定义类,则没有可用的close方法.我也尝试调用raw并给了我一个例外:

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) {

            }
        });

    }

如何关闭它?

推荐答案

此处您可以执行以下操作

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

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

希望它能解决您的问题.

Hope it will solve your issue.

这篇关于改造关闭响应体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆