1

我正在使用 Spray API(spray-client) 来访问外部 URL,并且我得到了 gzipped HttpResponse。如何解压缩此 HttpResponse 以获取其实体(在我的情况下为 json)?

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

在这里,json 被压缩。我如何解压缩它?

4

1 回答 1

5

您需要使用流水线和decode指令。就像在这个例子中一样。

修改该示例,您的代码将如下所示:

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

如果您不想要 Futures 的好处,您可以在响应上执行 Await。

在旁注中,您可以使用spray-json并为您的响应创建一个对象,然后将 http 响应直接解组到一个案例类中,而无需处理 json。

于 2014-08-27T16:01:45.663 回答