从webapp的客户端,我点击了服务器端路由,它只是第三方API的包装器.使用dispatch,我试图让服务器端请求返回第三方API到客户端AJAX调用的确切头和响应.
当我这样做:
val req = host("third-pary.api.com, 80)
val post = req.as("user", "pass") / "route" << Map("key" -> "akey", "val" -> "aval")
Http(post > as.String)
Run Code Online (Sandbox Code Playgroud)
我总是看到一个200响应返回到AJAX调用(有点预期).我已经看到了Either使用的语法,但我真的更像是一个Any,因为它只是确切的响应和标题.怎么写?
我应该提到我在服务器端使用Scalatra,因此本地路由是:
post("/route") {
}
Run Code Online (Sandbox Code Playgroud)
编辑:
这是我正在玩的建议的Either匹配示例,但match语法没有意义 - 我不在乎是否有错误,我只想返回它.此外,我似乎无法使用此方法返回BODY.
val asHeaders = as.Response { response =>
println("BODY: " + response.getResponseBody())
scala.collection.JavaConverters.mapAsScalaMapConverter(
response.getHeaders).asScala.toMap.mapValues(_.asScala.toList)
}
val response: Either[Throwable, Map[String, List[String]]] =
Http(post > asHeaders).either()
response match {
case Left(wrong) =>
println("Left: " + wrong.getMessage())
// return Action with header + body
case Right(good) =>
println("Right: " + good)
// return Action with header + body
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,解决方案会返回Scalatra ActionResult(responseStatus(status, reason), body, headers).
使用Dispatch时,实际上很容易获得响应头.例如0.9.4:
import dispatch._
import scala.collection.JavaConverters._
val headers: java.util.Map[String, java.util.List[String]] = Http(
url("http://www.google.com")
)().getHeaders
Run Code Online (Sandbox Code Playgroud)
现在,例如:
scala> headers.asScala.mapValues(_.asScala).foreach {
| case (k, v) => println(k + ": " + v)
| }
X-Frame-Options: Buffer(SAMEORIGIN)
Transfer-Encoding: Buffer(chunked)
Date: Buffer(Fri, 30 Nov 2012 20:42:45 GMT)
...
Run Code Online (Sandbox Code Playgroud)
如果你经常这样做,最好将它封装起来,例如:
val asHeaders = as.Response { response =>
scala.collection.JavaConverters.mapAsScalaMapConverter(
response.getHeaders
).asScala.toMap.mapValues(_.asScala.toList)
}
Run Code Online (Sandbox Code Playgroud)
现在您可以编写以下内容:
val response: Either[Throwable, Map[String, List[String]]] =
Http(url("http://www.google.com") OK asHeaders).either()
Run Code Online (Sandbox Code Playgroud)
而且你有错误检查,不可变的集合等等.