如何在 Play 和 Scala 中获取所有请求参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13355442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get all request parameters in Play and Scala
提问by Ryan Medlin
case GET(Path("/rtb_v1/bidrequest")) => Action { implicit request =>
I want to take the request object above and get all of the key/value pairs sent in the form post and flatten it into a Map[String,String]
我想获取上面的请求对象并获取表单帖子中发送的所有键/值对并将其展平为 Map[String,String]
i have gone through all the documents and am at a dead end.
我已经浏览了所有文件,但我走到了死胡同。
This is pretty freaking easy in Java/Servlets I;m wondering why there is no documentation on a simple thing like this anywhere..
这在 Java/Servlets 中非常容易,我想知道为什么在任何地方都没有关于这样简单事情的文档......
Map<String, String[]> parameters = request.getParameterMap();
回答by Kim Stebel
Play's equivalent of request.getParamterMapis request.queryString, which returns a Map[String, Seq[String]]. You can flatten it to a Map[String, String]with
Play 相当于request.getParamterMapis request.queryString,它返回一个Map[String, Seq[String]]。你可以把它展平到Map[String, String]与
request.queryString.map { case (k,v) => k -> v.mkString }
回答by Ivan Meredith
As an alternative to the way that Kim does it, I personally use a function like..
作为 Kim 的替代方法,我个人使用了一个函数,如..
def param(field: String): Option[String] =
request.queryString.get(field).flatMap(_.headOption)
回答by cchantep
It won't work if request is using POST method. Following code can be used:
如果请求使用 POST 方法,它将不起作用。可以使用以下代码:
req.body match {
case AnyContentAsFormUrlEncoded(params) ?
println(s"urlEncoded = $params")
case mp @ AnyContentAsMultipartFormData(_) ?
println(s"multipart = ${mp.asFormUrlEncoded}")
}
回答by Louis Querel
You might have to use the following:
您可能必须使用以下内容:
request.queryString.map { case (k,v) => k -> v.mkString }).toSeq: _*

