Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

akka HttpResponse read body as String scala

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

def apply(query: Seq[(String, String)], accept: String): HttpResponse

I simply get a value in a test like:

val resp = TagAPI(Seq.empty[(String, String)], api.acceptHeader)

I want to check its body in a test something like:

resp.entity.asString == "tags"

My question is how I can get the response body as string?

like image 722
tg44 Avatar asked Aug 31 '15 16:08

tg44


3 Answers

import akka.http.scaladsl.unmarshalling.Unmarshal

implicit val system = ActorSystem("System")  
implicit val materializer = ActorFlowMaterializer() 

val responseAsString: Future[String] = Unmarshal(entity).to[String]
like image 67
user3548738 Avatar answered Nov 07 '22 06:11

user3548738


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`
like image 31
Konrad 'ktoso' Malawski Avatar answered Nov 07 '22 05:11

Konrad 'ktoso' Malawski


You can also try this one also.

responseObject.entity.dataBytes.runFold(ByteString(""))(_ ++ _).map(_.utf8String) map println
like image 43
Shashank Jain Avatar answered Nov 07 '22 06:11

Shashank Jain