将Akka http实体字节字符串转换为Long

时间:2019-01-15 17:08:33

标签: scala akka akka-stream akka-http

如何从未知长度的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

1 个答案:

答案 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 
    }
}