OkHttp3連接接口時報錯FATAL EXCEPTION: OkHttp Dispatcher

報錯的情況類似這種:

12-10 11:05:55.176 8754-8796/ndk_demo.cyh.com.okhttp3demo E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher

出現這個問題的原因簡要說一下:

String json=response.body().string(); 

就是這行代碼中.string()方法使用次數超過了一次。

反正.string()方法只能使用一次,所以最常見的錯誤是什麼,定義了之後又把它打印出來,當然,打印json是沒問題的,但是打印response.body().string()就會報錯。看源碼發現當我們調用String()方法時,就會有close將流關閉掉,我們再次調用自然會報錯啦!

public final String string() throws IOException {
    BufferedSource source = source();
    try {
      Charset charset = Util.bomAwareCharset(source, charset());
      return source.readString(charset);
    } finally {
      Util.closeQuietly(source);
    }
  }

public static void closeQuietly(Closeable closeable) {
    if (closeable != null) {
      try {
        closeable.close();
      } catch (RuntimeException rethrown) {
        throw rethrown;
      } catch (Exception ignored) {
      }
    }
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章