我正在尝试实现Akka http客户端以进行邮寄请求,其中授权将在邮递员的标头中给出。我无法授权,以下是我的代码
def main(args: Array[String]) {
implicit val system: ActorSystem = ActorSystem()
implicit val materializer: ActorMaterializer = ActorMaterializer()
implicit val executionContext: ExecutionContextExecutor = system.dispatcher
val requestHeader = scala.collection.immutable.Seq(RawHeader("Authorization", "admin"))
val requestHandler: HttpRequest => HttpResponse = {
case HttpRequest(POST, Uri.Path("/GetTrackerData"), requestHeader, entity, _) =>
val chunk = Unmarshal(entity).to[DeviceLocationData]
val deviceLocationData = Await.result(chunk, 1.second)
val responseArray = "Authorized"
HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, responseArray)
)
case r: HttpRequest =>
println(r.uri.toString())
r.discardEntityBytes() // important to drain incoming HTTP Entity stream
HttpResponse(404, entity = "Unknown resource!")
}
val bindingFuture = Http().bindAndHandleSync(requestHandler, "0.0.0.0", 7070)
println(s"iot engine api live at 0.0.0.0:7070")
sys.addShutdownHook({
println("ShutdownHook called")
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
})
}
无论邮递员给我什么价值。它满足请求。我正在跳过什么?
我的用例是显示的结果仅在授权后才显示
您正在HttpRequest
上进行模式匹配。
您使用的requestHeader
不是您先前指定的,而是HttpRequest本身的headers。
一种解决方法可能是检查标题中的值:
case HttpRequest(HttpMethods.POST, Uri.Path("/GetTrackerData"), headers, entity, _)
if (headers.exists(h => h.name == "Authorization" && h.value == "admin")) =>
这里是一个问题:
case HttpRequest(POST, Uri.Path("/GetTrackerData"), requestHeader, entity, _) =>
这与requestHeader
的当前值不匹配,它将创建一个包含requestHeader
的当前标题的新值HttpRequest
。因此,此匹配项将不会检查标题的Authorization
字段。您将必须手动执行此操作。
更一般而言,值得一看的是Akka HTTP中对Route
的支持,这是一种更清洁,功能更强大的服务器实现方式。