OkHttp资源泄露问题

OkHttp的Response.body().string()方法会处理响应体并将其转换为字符串。此过程会检测BOM或Content-Type来确定charset,如果未指定则默认使用UTF-8。若响应体过大,加载到内存可能引发OutOfMemoryError,因此建议对大响应体进行流式处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OkHttp的返回值是Response, Response.body().string()会自动关闭流, 如果没有调用该方法, 需要手动关闭流: Response.body().close()

Response.body().string()源码, 使用了try语句关闭流

  /**
   * Returns the response as a string.
   *
   * <p>If the response starts with a <a href="https://en.wikipedia.org/wiki/Byte_order_mark">Byte
   * Order Mark (BOM)</a>, it is consumed and used to determine the charset of the response bytes.
   *
   * <p>Otherwise if the response has a Content-Type header that specifies a charset, that is used
   * to determine the charset of the response bytes.
   *
   * <p>Otherwise the response bytes are decoded as UTF-8.
   *
   * <p>This method loads entire response body into memory. If the response body is very large this
   * may trigger an {@link OutOfMemoryError}. Prefer to stream the response body if this is a
   * possibility for your response.
   */
  public final String string() throws IOException {
    try (BufferedSource source = source()) {
      Charset charset = Util.bomAwareCharset(source, charset());
      return source.readString(charset);
    }
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值