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) {
      }
    }
  }

猜你喜欢

转载自blog.csdn.net/u010194538/article/details/103471895