首页 > 解决方案 > scalaj-http - “执行”方法正在返回“流已关闭”

问题描述

我想使用 scalaj-http 库从 http 连接下载大小为 31gb 的字节内容文件。'asBytes' 不是一个选项,因为它返回一个字节数组。

我尝试使用返回输入流的“执行”方法,但是当我执行下面的程序时,它返回流已关闭。我不认为我正在阅读两次流。

我做错了什么?

  val response: HttpResponse[InputStream] = Http(url).postForm(parameters).execute(inputStream => inputStream)

  if (response.isError) println(s"Sorry, error found: ${response.code}")
  else {
    val is: InputStream = response.body
    val buffer: Array[Byte] = Array.ofDim[Byte](1024)
    val fos = new FileOutputStream("xxx")
    var read: Int = 0

    while (read >= 0) {
      read = is.read(buffer)
      if (read > 0) {
        fos.write(buffer, 0, read)
      }
    }
    fos.close()
  }

标签: scalastreamscalaj-http

解决方案


您无法导出,inputStream因为流将在执行方法结束时关闭。您应该在执行中使用流,如下所示:

  val response = Http(url).postForm(parameters).execute { is =>         
    val buffer: Array[Byte] = Array.ofDim[Byte](1024)
    val fos = new FileOutputStream("xxx")
    var read: Int = 0

    while (read >= 0) {
      read = is.read(buffer)
      if (read > 0) {
        fos.write(buffer, 0, read)
      }
    }
    fos.close()
  }

  if (response.isError) println(s"Sorry, error found: ${response.code}")

推荐阅读