akka HttpResponse read body as String scala

前端 未结 7 1007
广开言路
广开言路 2020-12-28 13:27

So I have a function with this signature (akka.http.model.HttpResponse):

def apply(query: Seq[(String, String)], accept: String): HttpResponse
7条回答
  •  长情又很酷
    2020-12-28 14:23

    Since Akka Http is streams based, the entity is streaming as well. If you really need the entire string at once, you can convert the incoming request into a Strict one:

    This is done by using the toStrict(timeout: FiniteDuration)(mat: Materializer) API to collect the request into a strict entity within a given time limit (this is important since you don't want to "try to collect the entity forever" in case the incoming request does actually never end):

    import akka.stream.ActorFlowMaterializer
    import akka.actor.ActorSystem
    
    implicit val system = ActorSystem("Sys") // your actor system, only 1 per app
    implicit val materializer = ActorFlowMaterializer() // you must provide a materializer
    
    import system.dispatcher
    import scala.concurrent.duration._
    val timeout = 300.millis
    
    val bs: Future[ByteString] = entity.toStrict(timeout).map { _.data }
    val s: Future[String] = bs.map(_.utf8String) // if you indeed need a `String`
    

提交回复
热议问题