Transform Akka http entity byte string to Long

akka-http

(vamsi) #1

How to read long from an Akka-HTTP response stream of an unknown length?

example :

          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

          }

how can we transform ByteString to the Long the above stream?


(Johan Andrén) #2

Is the body a string representation of the number, your sample code seems to indicate that there are sub-elements in the body somehow?

You likely will want to collect the entire body into memory first as how the individual ByteString chunks are split up can be arbitrary depending on network etc. You can do that with entity.toStrict, something like this:

if (response.status == StatusCodes.OK) 
  response.entity.toStrict(10.seconds)
    .map { entireBody =>
      val text = entireBody.data.decodeString(StandardCharsets.UTF_8)
      text.toLong
    }