【问题标题】:Spray Unzip HttpResponse喷解压 HttpResponse
【发布时间】:2014-08-26 21:47:46
【问题描述】:

我正在使用 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 被压缩了。怎么解压?

【问题讨论】:

    标签: scala gzip spray-client


    【解决方案1】:

    您需要使用流水线和decode 指令。就像在这个example.

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

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

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

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

    【讨论】:

    • 很高兴能帮上忙。不要忘记接受答案。
    猜你喜欢
    • 1970-01-01
    • 2011-06-25
    • 2014-03-06
    • 2016-02-24
    • 1970-01-01
    • 2015-10-27
    • 2012-10-03
    • 2015-03-03
    • 2013-10-02
    相关资源
    最近更新 更多