Databinder调度:获取403响应的未压缩内容

时间:2012-05-28 21:06:05

标签: scala scala-dispatch

我正在使用databinder dispatch来发出很好的HTTP请求,只要Web服务器返回404。

如果请求失败,Web服务器将返回403状态代码,并在响应正文中以XML格式提供详细的错误消息。

如何读取xml正文(无论403),例如如何使调度忽略所有403错误?

我的代码如下所示:

class HttpApiService(val apiAccount:ApiAccount) extends ApiService {
  val http = new Http

  override def baseUrl() = "http://ws.audioscrobbler.com/2.0"

  def service(call:Call) : Response = {
    val http = new Http
    var req = url(baseUrl())
    var params = call.getParameterMap(apiAccount)

    var response: NodeSeq = Text("")

    var request: Request = constructRequest(call, req, params)
    // Here a StatusCode exception is thrown. 
    // Cannot use StatusCode case matching because of GZIP compression
    http(request <> {response = _})
    //returns the parsed xml response as NodeSeq
    Response(response)
  }

  private def constructRequest(call: Call, req: Request, params: Map[String, String]): Request = {
    val request: Request = call match {
      case authCall: AuthenticatedCall =>
        if (authCall.isWriteRequest) req <<< params else req <<? params
      case _ => req <<? params
    }
    //Enable gzip compression
    request.gzip
  }
}

1 个答案:

答案 0 :(得分:2)

相信这样的作品:

val response: Either[String, xml.Elem] = 
  try { 
    Right(http(request <> { r => r })) 
  } catch { 
    case dispatch.StatusCode(403, contents) => 
      Left(contents)
  }

错误将在左侧。成功将在Right。错误是一个字符串,应该包含您想要的XML响应。

如果您需要更多,我相信您可以查看HttpExecutor.x,它可以让您完全控制。但是,自从我使用调度以来已经有一段时间了。

另外,我建议使用更多的val和更少的var。