我想从调度请求中获取正文和标头。这个怎么做?
val response = Http(request OK as.String)
for (r <- response) yield {
println(r.toString) //prints body
// println(r.getHeaders) // ???? how to print headers here ????
}
我想从调度请求中获取正文和标头。这个怎么做?
val response = Http(request OK as.String)
for (r <- response) yield {
println(r.toString) //prints body
// println(r.getHeaders) // ???? how to print headers here ????
}
我们需要对 API 的失败请求的响应体,所以我们想出了这个解决方案:
用and定义你自己的ApiHttpError
类(对于正文):
code
body
case class ApiHttpError(code: Int, body: String)
extends Exception("Unexpected response status: %d".format(code))
定义OkWithBodyHandler
类似于源代码中使用的内容displatch
:
class OkWithBodyHandler[T](f: Response => T) extends AsyncCompletionHandler[T] {
def onCompleted(response: Response) = {
if (response.getStatusCode / 100 == 2) {
f(response)
} else {
throw ApiHttpError(response.getStatusCode, response.getResponseBody)
}
}
}
现在,在您对可能抛出和异常的代码(调用API
)的调用附近,将implicit
覆盖添加到ToupleBuilder
(再次类似于源代码)并OkWithBody
调用request
:
class MyApiService {
implicit class MyRequestHandlerTupleBuilder(req: Req) {
def OKWithBody[T](f: Response => T) =
(req.toRequest, new OkWithBodyHandler(f))
}
def callApi(request: Req) = {
Http(request OKWithBody as.String).either
}
}
从现在开始,fetchingeither
会给你[Throwable, String]
(using as.String)
, and the Throwable
is our ApiHttpError
with code
and body
.
希望它有所帮助。
从调度文档:
import dispatch._, Defaults._ val svc = url("http://api.hostip.info/country.php") val country = Http(svc OK as.String)
上面定义并向给定主机发起请求,其中 2xx 响应作为字符串处理。由于 Dispatch 是完全异步的,因此 country 代表字符串的未来而不是字符串本身。(来源)
在您的示例中,响应的类型是 Future[String],因为“OK as.String”将 2xx 响应转换为字符串,将非 2xx 响应转换为失败的期货。如果你删除 'OK as.String',你会得到一个 Future[com.ning.http.client.Response]。然后,您可以使用 getResponseBody、getHeaders 等来检查 Request 对象。