使用 Finagle Http 客户端下载文件
Download file with Finagle Http Client
我正在尝试从远程文件中获取一个字节数组。我创建了 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?
})
你不需要fromReader
,AsyncStream
已经有了。
所以,你可以这样做:
val result: Future[Array[Byte]] = response
.flatMap { resp =>
AsyncStream.fromReader(resp.reader)
.foldLeft(Buf.Empty){ _ concat _ }
.map(Buf.ByteArray.Owned.extract)
}
使用 scalaj
下载文件。
import scalaj.http._
val response: HttpResponse[String] = Http("http://foo.com/search").param("q","monkeys").asString
请参阅有关不同类型请求的文档 Get、Post 等
我正在尝试从远程文件中获取一个字节数组。我创建了 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?
})
你不需要fromReader
,AsyncStream
已经有了。
所以,你可以这样做:
val result: Future[Array[Byte]] = response
.flatMap { resp =>
AsyncStream.fromReader(resp.reader)
.foldLeft(Buf.Empty){ _ concat _ }
.map(Buf.ByteArray.Owned.extract)
}
使用 scalaj
下载文件。
import scalaj.http._
val response: HttpResponse[String] = Http("http://foo.com/search").param("q","monkeys").asString
请参阅有关不同类型请求的文档 Get、Post 等