解決okhttp3提示java.lang.IllegalStateException:closed異常問題
okhttp3提示java.lang.IllegalStateException:closed異常
使用okhttp3的response.body().string()時候提示java.lang.IllegalStateException: closed異常
原因為okhttp3請求回調(diào)中response.body().string()只能有效調(diào)用一次,而我使用了兩次,所以在第二次時調(diào)用時提示已關閉流的異常。
Response response = httpClient.newCall(request).execute(); logger.info(response.body().string()); //一次 Map<String,Object> resMap=objectMapper.readValue(response.body().string(),Map.class); //兩次
解決辦法
將返回的值保存在對象中,重復使用對象即可。(或者重新builder一個Response對象)
public void pushOrder(RecordPushRequest pushRequest) throws Exception { //TODO:構造builder Request.Builder builder = new Request.Builder() .url(URL) .header("Content_Type", "application/json"); //TODO:構造請求體 RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), objectMapper.writeValueAsString(pushRequest)); //TODO:構造請求 Request request = builder.post(requestBody).build(); //TODO:發(fā)起請求 Response response = httpClient.newCall(request).execute(); String res = response.body().string(); // logger.info(response.body().string()); //打印時重復使用了一次 Map<String,Object> resMap=objectMapper.readValue(res,Map.class); logger.info("得到的響應解析結(jié)果:{} ",resMap); }
深扒response.body().string()問題原因
查看源碼Response.class:
private final ResponseBody body;
發(fā)現(xiàn)body是一個ResponseBody 對象。繼續(xù)查看ResponseBody 類的源碼:
public abstract class ResponseBody implements Closeable
ResponseBody類實現(xiàn)Closeable接口,感覺有點找到問題的源泉了,繼續(xù)點進去看看Closeable接口是干嘛的:
public interface Closeable extends AutoCloseable { /** * Closes this stream and releases any system resources associated * with it. If the stream is already closed then invoking this * method has no effect. * * <p> As noted in {@link AutoCloseable#close()}, cases where the * close may fail require careful attention. It is strongly advised * to relinquish the underlying resources and to internally * <em>mark</em> the {@code Closeable} as closed, prior to throwing * the {@code IOException}. * * @throws IOException if an I/O error occurs */ public void close() throws IOException; }
Closeable接口繼承AutoCloseable類,有一個close方法,官方標注:“關閉此流并釋放與之關聯(lián)的任何系統(tǒng)資源。
如果流已關閉,則調(diào)用此方法無效。”大概就是這個原因了。所以不要多次調(diào)用response.body().string();語句。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java.lang.OutOfMemoryError 錯誤整理及解決辦法
這篇文章主要介紹了java.lang.OutOfMemoryError 錯誤整理及解決辦法的相關資料,需要的朋友可以參考下2016-10-10SpringBoot中API接口參數(shù)獲取方式小結(jié)
在Spring Boot中,API接口參數(shù)可以通過多種方式獲取,具體取決于你定義的API接口參數(shù)類型(如路徑參數(shù)、查詢參數(shù)、請求體參數(shù)、請求頭等),本文給大家就介紹了一些常見的參數(shù)獲取方式,需要的朋友可以參考下2024-06-06MyBatis批量查詢、插入、更新、刪除的實現(xiàn)示例
由于需要處理短時間內(nèi)大量數(shù)據(jù)入庫的問題,想到了Mybatis的批量操作,本文主要介紹了MyBatis批量查詢、插入、更新、刪除的實現(xiàn)示例,感興趣的可以了解一下2023-05-05解決Mybatis查詢方法selectById()主鍵不一致問題
這篇文章主要介紹了解決Mybatis查詢方法selectById()主鍵不一致問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10