>我正在使用数据绑定器调度来发出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
}
}
我相信这样的东西有效:
val response: Either[String, xml.Elem] =
try {
Right(http(request <> { r => r }))
} catch {
case dispatch.StatusCode(403, contents) =>
Left(contents)
}
错误将出现在左侧。 成功将在正确。 错误是一个字符串,应包含所需的 XML 响应。
如果你需要更多,我相信你可以看看HttpExecutor.x,它应该可以让你完全控制。 不过,我已经有一段时间没有使用调度了。
另外,我建议使用更多的val和更少的var。