scalaj-http - 'execute' 方法正在返回 "stream is closed"

scalaj-http - 'execute' method is returninig "stream is closed"

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

我尝试使用 'execute' 方法返回一个输入流,但是当我执行下面的程序时 returns 该流被关闭了。我不认为我正在阅读两次流。

我做错了什么?

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

您无法导出 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}")