如何从未知长度的Akka-HTTP响应流中读取较长内容?
示例:
val futureResponse = Http(system).singleRequest(
HttpRequest(
HttpMethods.POST,
"url",
entity = HttpEntity(ContentTypes.`application/json`, "somequery".getBytes())
).withHeaders(RawHeader("X-Access-Token", "access token"))
)
futureResponse.map {
res =>
res.entity.dataBytes
.map(convertToLong) // convert to long/int
.grouped(2) // group two elments together
.map(getRelation)// do some transform
.runWith(someSink) // write to sink
}
我们如何将ByteString
转换为以上流的Long
?
答案 0 :(得分:1)
编写一个使用ByteString并返回Long ByteString选项的函数=> Option [Long]
def toLong(x: ByteString): Option[Long] = {
try{
Some(x.decodeString("UTF-8").toLong)
} catch {
case e: Exception => None
}
}