在Scala Dispatch中解码流式GZIP响应?

时间:2013-04-04 00:08:50

标签: scala scala-dispatch asynchttpclient

从API接收Gzip响应,但Dispatch 0.9.5似乎没有任何解码响应的方法。有什么想法吗?

这是我当前的实现,println只打印出字节的字符串表示。

   Http(
      host("stream.gnip.com")
      .secure
      .addHeader("Accept-Encoding", "gzip")
       / gnipUrl
      > as.stream.Lines(println))()

试图看看实现我自己的处理程序,但不知道从哪里开始。以下是Lineshttps://github.com/dispatch/reboot/blob/master/core/src/main/scala/as/stream/lines.scala

的相关文件

谢谢!

4 个答案:

答案 0 :(得分:2)

简单地放弃Dispatch并直接使用Java API。令人失望,但它完成了工作。

  val GNIP_URL = isDev match {
    case true => "https://url/apath/track/dev.json"
    case false => "https://url/path/track/prod.json"
  }
  val GNIP_CHARSET = "UTF-8"

  override def preStart() = {
    log.info("[tracker] Starting new Twitter PowerTrack connection to %s" format GNIP_URL)

    val connection = getConnection(GNIP_URL, GNIP_USER, GNIP_PASSWORD)
    val inputStream = connection.getInputStream()
    val reader = new BufferedReader(new InputStreamReader(new StreamingGZIPInputStream(inputStream), GNIP_CHARSET))
    var line = reader.readLine()
    while(line != null){
        println(line)
        line = reader.readLine()
    }
  }

  private def getConnection(urlString: String, user: String, password: String): HttpURLConnection = {
    val url = new URL(urlString)

    val connection = url.openConnection().asInstanceOf[HttpURLConnection]
    connection.setReadTimeout(1000 * 60 * 60)
    connection.setConnectTimeout(1000 * 10)

    connection.setRequestProperty("Authorization", createAuthHeader(user, password));
    connection.setRequestProperty("Accept-Encoding", "gzip")
    connection
  }

  private def createAuthHeader(username: String, password: String) = {
    val encoder = new BASE64Encoder()
    val authToken = username+":"+password
   "Basic "+encoder.encode(authToken.getBytes())
  }

使用GNIP的示例:https://github.com/gnip/support/blob/master/Premium%20Stream%20Connection/Java/StreamingConnection.java

答案 1 :(得分:2)

这不是一个解决方案作为一种解决方法,但我最终试图绕过基于Future的东西并做:

val stream = Http(req OK as.Response(_.getResponseBodyAsStream)).apply val result = JsonParser.parse( new java.io.InputStreamReader( new java.util.zip.GZIPInputStream(stream)))

我在这里使用JsonParser,因为在我的情况下,我收到的数据恰好是JSON;如果需要,用你的用例中的其他东西替换。

答案 2 :(得分:2)

我的解决方案刚刚定义了一个响应解析器,并且还采用了json4s解析器:

    import GzipJson._

    Http(req OK GzipJson).apply

这样我就可以使用它来提取Gzip Json响应,如下面的代码所示:

Sheets("RAW").Cells(i, lastcol).Value2 = _
    Hour(TimeValue(Sheets("RAW").Cells(i, 7).Value2)) * 60 _
    + Minute(TimeValue(Sheets("RAW").Cells(i, 7).Value2))

答案 3 :(得分:-1)