Dan*_*ier 2 scala header http request scala-dispatch
我想从调度请求中获取正文和标头。这该怎么做?
val response = Http(request OK as.String)
for (r <- response) yield {
println(r.toString) //prints body
// println(r.getHeaders) // ???? how to print headers here ????
}
Run Code Online (Sandbox Code Playgroud)
我们需要对API失败请求的响应主体,因此我们提出了以下解决方案:
ApiHttpError使用code和定义您自己的类body(对于正文):
case class ApiHttpError(code: Int, body: String)
extends Exception("Unexpected response status: %d".format(code))
Run Code Online (Sandbox Code Playgroud)
定义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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,你的附近调用可能抛出和异常(调用的代码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
}
}
Run Code Online (Sandbox Code Playgroud)
从现在开始,抓取either将为您提供[Throwable, String](using as.String)和the Throwable是我们的ApiHttpErrorwith code和body。
希望能有所帮助。
| 归档时间: |
|
| 查看次数: |
1610 次 |
| 最近记录: |