okhttp - 非法状态异常 : response is not eligible for a body and must not be closed

标签 okhttp

有时我们会得到这个异常处理响应。 Response 似乎有一个 null 主体。

代码是这样的:

try (Response response = client.newCall(request).execute()) {
  // do stuff with the response
} catch (Exception e) {
  log.error("Something wrong", e);
}

do stuff with response block 执行后,在 Response 上自动调用的 close() 方法引发异常。

堆栈跟踪:

java.lang.IllegalStateException: response is not eligible for a body and must not be closed
    at okhttp3.Response.close(Response.java:281)

我们是否遗漏了什么?
谢谢。

最佳答案

我认为你可以调用 response.body.close()response.close() 相同,并在关闭前检查 body 是否为 null。

        ResponseBody responseBody = null;
        try {
            Response response = client.newCall(request).execute();
            responseBody = response.body();
            // do stuff with the response
        } catch (Exception e) {
            log.error("Something wrong", e);
        } finally {
            if (responseBody != null) {
                responseBody.close();
            }
        }

关于okhttp - 非法状态异常 : response is not eligible for a body and must not be closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51627097/

相关文章:

java - 如何检测Android中的上传/下载传输速率?

Kotlin 下载并显示 PDF

android - 在 Picasso 客户端上设置自定义 HTTP 客户端缓存的影响

android - HttpLoggingInterceptor (OkHttp3) 为每个请求记录很多次

java - Gradle 错误 - 无法下载 okhttp.jar 文件 2.7.2

java - 改造添加带有 token 和 ID 的 header

android - 如何使用 OkHTTP3/Retrofit2 获取多部分多文件上传的进度?

java - JDK8 -> JDK10 : PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested target

java - OkHttp3 多请求标签

android - 多部分请求spring不绑定(bind)文件数据