【问题标题】:Retrofit Closing Response Body改造关闭响应机构
【发布时间】:2017-01-21 19:00:29
【问题描述】:

我收到了这个错误:

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

所以我继续关闭收到的回复。

response.body().close()

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

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

            }
        });

    }

如何关闭它?

【问题讨论】:

  • retrofit 和 okhttp 版本是什么?
  • 编译 'com.squareup.retrofit2:retrofit:2.0.0-beta4' 编译 'com.squareup.retrofit2:converter-jackson:2.0.0-beta4' 编译 'com.squareup.okhttp3: logging-interceptor:3.2.0' 编译 "com.squareup.okhttp3:okhttp-urlconnection:3.0.1"
  • 能否更新retrofit和okhttp库并再次检查代码。
  • 那些是非常旧的版本。更新并重试。 Retrofit 2 为你关闭了 ResponseBody;无需在应用层这样做。
  • 这成功了,谢谢@EricCochran

标签: android retrofit retrofit2 okhttp okhttp3


【解决方案1】:

如here 所述,您可以执行以下操作

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

希望它能解决您的问题。

【讨论】:

  • 返回:371-11371/com.billbii.billbiiapplication E/AndroidRuntime:致命异常:主进程:com.billbii.billbiiapplication,PID:11371 java.lang.IllegalStateException:无法读取原始响应正文转换后的身体。
  • @KimMontano 你有什么解决办法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
相关资源
最近更新 更多