我知道喷雾为我做了这个,但我仍然希望用我的标题覆盖它,我怎样才能覆盖响应中的标题?
我的回答如下:
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
sender ! HttpResponse(entity = """{ "key": "value" }""" // here i want to specify also response header i would like to explicitly set it and not get it implicitly
Run Code Online (Sandbox Code Playgroud)
4le*_*x1v 14
如果你仍然想使用喷雾罐,那么你有两个选择,基于HttpResponse是一个案例类.第一种是传递具有显式内容类型的List:
import spray.http.HttpHeaders._
import spray.http.ContentTypes._
def receive = {
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
sender ! HttpResponse(entity = """{ "key": "value" }""", headers = List(`Content-Type`(`application/json`)))
}
Run Code Online (Sandbox Code Playgroud)
或者,第二种方法是使用方法withHeaders方法:
def receive = {
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
val response: HttpResponse = HttpResponse(entity = """{ "key": "value" }""")
sender ! response.withHeaders(List(`Content-Type`(`application/json`)))
}
Run Code Online (Sandbox Code Playgroud)
但是,就像jrudolph说的那样,使用喷涂路由要好得多,在这种情况下它看起来会更好:
def receive = runRoute {
path("/something") {
get {
respondWithHeader(`Content-Type`(`application/json`)) {
complete("""{ "key": "value" }""")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但喷雾使它更容易,并为您处理所有(联合国)编组:
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
def receive = runRoute {
(path("/something") & get) {
complete(Map("key" -> "value"))
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,响应类型将由application/json喷雾本身设置.
我的评论的完整示例:
class FullProfileServiceStack
extends HttpServiceActor
with ProfileServiceStack
with ... {
def actorRefFactory = context
def receive = runRoute(serviceRoutes)
}
object Launcher extends App {
import Settings.service._
implicit val system = ActorSystem("Profile-Service")
import system.log
log.info("Starting service actor")
val handler = system.actorOf(Props[FullProfileServiceStack], "ProfileActor")
log.info("Starting Http connection")
IO(Http) ! Http.Bind(handler, interface = host, port = port)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12106 次 |
| 最近记录: |