有时我们会得到这个异常处理响应。
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/