4

从 API 接收 Gzipped 响应,但 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

4 回答 4

3

干脆放弃了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

于 2013-04-04T17:42:36.073 回答
3

这与其说是一种解决方案,不如说是一种解决方法,但我最终求助于绕过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;如果需要,用你的用例中的其他东西代替。

于 2014-03-24T23:29:09.940 回答
2

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

    object GzipJson extends (Response => JValue) {
      def apply(r: Response) = {
        if(r.getHeader("content-encoding")!=null && r.getHeader("content-encoding").equals("gzip")){
          (parse(new GZIPInputStream(r.getResponseBodyAsStream), true))
        }else
          (dispatch.as.String andThen (s => parse(StringInput(s), true)))(r)
      }
    }

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

    import GzipJson._

    Http(req OK GzipJson).apply
于 2015-07-27T10:46:54.227 回答
-1

尝试>>代替>

https://github.com/dispatch/dispatch/blob/master/core/src/main/scala/handlers.scala#L58

于 2013-04-04T02:20:40.493 回答