解决
java.lang.IllegalStateException: closed
异常通常是由于OkHttp中的Response
对象在调用response.body().string()
后被关闭而导致的。
在代码中,在onResponse()
方法中如果两次调用了response.body().string()
,每次调用都会消耗掉响应体并关闭Response
对象。因此,当第二次调用response.body().string()
时,就会抛出java.lang.IllegalStateException: closed
异常。
为了解决这个问题,可以将响应体的内容缓存起来,然后多次使用。下面是修改后的代码示例:
public void onResponse(Call call, Response response) throws IOException {String responseBody = response.body().string(); // 缓存响应体内容if (!response.isSuccessful()) {callback.onComponentInitFinish(COMPONENT_TOKEN, ERROR_GET_TOKEN_FAIL, "获取token失败");} else {TokenInfoBean tokenInfoBean = mGson.fromJson(responseBody, TokenInfoBean.class);if (tokenInfoBean != null && tokenInfoBean.ret != null) {APIBase.okHandler.post(new Runnable() {public void run() {KeyCenterCheckHelp.checkAndToast(tokenInfoBean.ret.code, tokenInfoBean.ret.message);}});}if (tokenInfoBean != null && tokenInfoBean.data != null) {savedToken = tokenInfoBean.data.token;tokenStartStamp = System.currentTimeMillis();tokenExpiredStamp = tokenStartStamp + tokenInfoBean.data.duration * 1000;callback.onComponentInitFinish(COMPONENT_TOKEN, 0, "");} else {callback.onComponentInitFinish(COMPONENT_TOKEN, tokenInfoBean.ret.code, tokenInfoBean.ret.message);}}
}
在修改后的代码中,我们将response.body().string()
的结果缓存在responseBody
变量中,并在后续的逻辑中多次使用。这样就避免了多次调用导致的异常。
请注意,这只是解决java.lang.IllegalStateException: closed
异常的一种方式。确保在其他地方没有关闭Response
对象,以免引发其他类似的异常。
重要代码:
String responseBody = response.body().string(); // 缓存响应体内容