akka HttpResponse read body as String scala

前端 未结 7 996
广开言路
广开言路 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:09

    Unfortunately in my case, Unmarshal to String didn't work properly complaining on: Unsupported Content-Type, supported: application/json. That would be more elegant solution, but I had to use another way. In my test I used Future extracted from entity of the response and Await (from scala.concurrent) to get the result from the Future:

    Put("/post/item", requestEntity) ~> route ~> check {
      val responseContent: Future[Option[String]] =
      response.entity.dataBytes.map(_.utf8String).runWith(Sink.lastOption)
    
      val content: Option[String] = Await.result(responseContent, 10.seconds)
      content.get should be(errorMessage)
      response.status should be(StatusCodes.InternalServerError)
    }
    

    If you need to go through all lines in a response, you can use runForeach of Source:

     response.entity.dataBytes.map(_.utf8String).runForeach(data => println(data))
    

提交回复
热议问题