【问题标题】:Download file with Finagle Http Client使用 Finagle Http 客户端下载文件
【发布时间】:2017-06-23 01:56:47
【问题描述】:

我正在尝试从远程文件中获取一个字节数组。我创建了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?
    })

【问题讨论】:

    标签: scala finagle


    【解决方案1】:

    你不需要fromReaderAsyncStream 已经有了。 所以,你可以这样做:

    val result: Future[Array[Byte]] = response
      .flatMap { resp => 
        AsyncStream.fromReader(resp.reader)
          .foldLeft(Buf.Empty){ _ concat _ }
          .map(Buf.ByteArray.Owned.extract)
      }
    

    【讨论】:

      【解决方案2】:

      使用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

      【讨论】:

        猜你喜欢
        • 2018-04-29
        • 1970-01-01
        • 1970-01-01
        • 2013-06-26
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 2011-04-30
        • 1970-01-01
        相关资源
        最近更新 更多