打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
java.lang.IllegalStateException: closed

1.android studio 
添加compile ‘com.squareup.okhttp3:okhttp:3.4.1’ 
更新版本可以再github上寻找到 
2.请求网络数据 
基本用法:

 String szURL = url;OkHttpClient okHttpClient = new OkHttpClient();okhttp3.Request request = new okhttp3.Request.Builder().url(szURL).build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Log.e("zht", "onFailure() e=" + e);}@Overridepublic void onResponse(Call call, final Response response) throws IOException {              Log.i("zht",response.body().string());}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

1.okhttp自带异步处理,可以封装到方法中直接调用,也可以开启子线程中使用okhttp 
2.response 只能用一次,这一次使用的机会包含log,包含log,包含log 
response.body().string()转换为string,适用于内容小于1m的

如果你如此之写

@Overridepublic void onResponse(Call call, final Response response) throws IOException {Log.i("zht",response.body().string());String reuslt = response.body().string();}
  • 1
  • 2
  • 3
  • 4
  • 5
那么会报错 
截图如下 
03-31 10:25:10.682 W/System.err( 2277): java.lang.IllegalStateException: closed
03-31 10:25:10.683 W/System.err( 2277):         at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:398)
03-31 10:25:10.683 W/System.err( 2277):         at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:392)
03-31 10:25:10.684 W/System.err( 2277):         at okhttp3.internal.Util.bomAwareCharset(Util.java:431)
03-31 10:25:10.684 W/System.err( 2277):         at okhttp3.ResponseBody.string(ResponseBody.java:174)
03-31 10:25:10.685 W/System.err( 2277):         at com.androidmov.monitor.Tr069JNI$7.run(Tr069JNI.java:967)

java.lang.IllegalStateException: closed 
这个错误 
所以只可以用一次response.body().string(),你可以将response.body().string()保存到string result中 
就可以。


返回大量的json数据,文件超过1m了,比如从聚合上获取新闻 
最为简单的处理方法: 
这里我们使用Gson,gson支持reader转换为bean,减少了过程,使用自带的缓冲区

Reader reader = response.body().charStream();HotNewsBean bean=new HotNewsBean();Gson gson=new Gson();bean=gson.fromJson(reader,HotNewsBean.class);
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
java.lang.IllegalStateException: circular reference error Gson循环引用
纠结了半天的 java.lang.IllegalStateException: getOutputStream() has already been called for this response
java.lang.IllegalStateException:Cannot forward after response has been committed
Android Volley OkHttp3 Gson(Jackson)的封装过程
java.lang.IllegalStateException异常:简单分析和简单解决方案
Android OkHttp完全解析 是时候来了解OkHttp了
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服