我想解构从服务器
获得的HttpResponse
Success(HttpResponse(200 OK,List(Server: akka-http/2.3.12, Date: Tue, 04 Aug 2015 22:20:21 GMT),HttpEntity.Default(application/json,69,akka.stream.scaladsl.Source@52ffaba9),HttpProtocol(HTTP/1.1)))
我看了documentation,但我不确定如何解构它
我正在尝试的方式是
val responseFuture: Future[HttpResponse] =
Http().singleRequest(HttpRequest(uri = "http://localhost:8080"))
responseFuture onComplete {
case Success(_) =>
log.info("response received {}", response)
log.info("notified about EC Failure")
}
但我不确定模式匹配的有效方法是什么
答案 0 :(得分:2)
像Scala中的其他monadic类型一样处理期货...... map
,flatMap
,forEach
和朋友:
val responseFuture: Future[HttpResponse] =
Http().singleRequest(HttpRequest(uri = "http://localhost:8080"))
responseFuture forEach { response =>
log.info("response received {}", response)
log.info("notified about EC Failure")
}
// or
for(response <- responseFuture) {
log.info("response received {}", response)
log.info("notified about EC Failure")
}
答案 1 :(得分:1)
像这样:
responseFuture onComplete {
case (Success(HttpResponse(statusCode, header, entity, protocol)), _) =>
log.info("Request returned status code {} with entity {}", statusCode, entity)
case (Failure(response), _) =>
log.info("Request failed with response {}", response)
}
您可以通过与akka.http.scaladsl.model.StatusCodes
匹配并添加更多案例来处理特定的状态代码。
答案 2 :(得分:0)
您可以捕获Success
内的HttpResponse
类型,并将其分配给您可以在模式匹配块中使用的变量。如果Success
包含HttpResponse
,则会将其分配给变量hr
,然后我们可以使用HttpResponse
访问类hr
上的方法。
case Success(hr:HttpResponse) =>
log.info("HTTP code: " + hr.status)
}