使用Finagle Http Client下载文件

时间:2017-06-23 01:56:47

标签: scala finagle

我正在尝试从远程文件中获取一个字节数组。我创建了AsyncStream,但不知道如何将其转换为正确的字节数组。

  val client: Service[http.Request, http.Response] =
    Http
      .client
      .withStreaming(enabled = true)
      .newService("www.scala-lang.org:80")

  val request = http.Request(http.Method.Get, "/docu/files/ScalaOverview.pdf")
  request.host = "scala-lang.org"
  val response: Future[http.Response] = client(request)

  def fromReader(reader: Reader): AsyncStream[Buf] =
    AsyncStream.fromFuture(reader.read(Int.MaxValue)).flatMap {
      case None => AsyncStream.empty
      case Some(a) => a +:: fromReader(reader)
    }

  val result: Array[Byte] =
    Await.result(response.flatMap {
      case resp =>
        fromReader(resp.reader) ??? // what to do?
    })

1 个答案:

答案 0 :(得分:1)

使用scalaj下载文件。

import scalaj.http._

val response: HttpResponse[String] = Http("http://foo.com/search").param("q","monkeys").asString

请参阅文档,了解不同类型的请求Get,Post等。

https://github.com/scalaj/scalaj-http