Spray Unzip HttpResponse

2019-07-31 17:22发布

问题:

I'm using Spray API(spray-client) to hit an external URL and I'm getting gzipped HttpResponse. How do I unzip this HttpResponse to get its entity(json, in my case)?

val future: Future[HttpResponse] = (IO(Http) ? Get(uri)).mapTo[HttpResponse]
val response = Await.result(future, Duration.inf)
val json = response.entity

Here, json is gzipped. How do I unzip it?

回答1:

You need to use pipelining and the decode directive. Like in this example.

Modifying that example your code would look something like this:

val pipeline: HttpRequest => Future[String] = (
  sendReceive
  ~> decode(Gzip)
  ~> unmarshal[String]
)
val response: Future[String] =
  pipeline(Get(uri))

You can then do Await on the response if you don't want the benefits of Futures.

On a side note you can use spray-json and create an object for your response and then unmarshal the http response directly into a case class without having to deal with the json.