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

174 views Asked by At

I want to use the scalaj-http library to download a byte content file with 31gb size from a http connection. 'asBytes' is not an option because it retuns a byte array.

I tried to use the 'execute' method returning an input stream, but when I execute the program bellow it returns that the stream is closed. I don't think that I am reading the stream twice.

What I am doing wrong?

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

There are 1 answers

0
danoliv On BEST ANSWER

You cannot export the inputStream as the stream will be closed at the end of the execute method. You should use the stream inside the execute, like this :

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