scala 如何从 Play 2.0 中的 POST 获取有效载荷

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8620076/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:46:12  来源:igfitidea点击:

How to get payload from a POST in Play 2.0

scalaplayframework-2.0

提问by jglatre

I'm trying to implement a REST API with Play 2.0 (Scala) but I'm getting stuck in POST method. How do I get the payload from Request object? I haven't find any documentation about it and have been unable to figure out from source code.

我正在尝试使用 Play 2.0 (Scala) 实现 REST API,但我陷入了 POST 方法的困境。如何从 Request 对象获取有效负载?我没有找到任何关于它的文档,也无法从源代码中找出答案。

采纳答案by chiappone

You should be able to do the following:

您应该能够执行以下操作:

def index = Action { request =>
  val body = request.body
}

And also things like:

还有这样的事情:

def index = Action { request =>
  val name = request.queryString.get("name").flatMap(_.headOption)
  Ok("Hello " + name.getOrElse("Guest"))
}

回答by opensas

have a look at this articleon playlatam

看看这篇关于playlatam 的文章

also check this questionon google list

也检查谷歌列表上的这个问题

for java (with a param names java_name):

对于 java(带有参数名称 java_name):

String name = request().body().asFormUrlEncoded().get("java_name")[0];

for scala (with a param names scala_name):

对于 scala(带有参数名称 scala_name):

def name = request.body.asFormUrlEncoded.get("scala_name")(0)

回答by ed.

I had to do it somewhat differently (maybe I'm on a newer version of the codebase):

我不得不做一些不同的事情(也许我使用的是较新版本的代码库):

my javascript:

我的javascript:

$(document).ready(function(){
  $.post( "/ping", {one: "one", two: "two" },
    function( data ){
      console.log(data); //returns {"one":"one","two":"two"}
    })
});

my route:

我的路线:

POST /ping controllers.Application.ping()

My controller method:

我的控制器方法:

def ping() = Action{ request =>

  val map : Map[String,Seq[String]] = request.body.asFormUrlEncoded.getOrElse(Map())

  val one : Seq[String] = map.getOrElse("one", List[String]())
  val two : Seq[String] = map.getOrElse("two", List[String]())

  Ok( 
    toJson( JsObject(List( "one"->JsString(one.first), "two"->JsString(two.first))))
  )
}

I assume this will change in the final version.

我认为这会在最终版本中改变。

回答by angelokh

Here is what I did.

这是我所做的。

val map : Map[String,Seq[String]] = request.body
val seq1 : Seq[String] = map.getOrElse("socket_id", Seq[String]())
val seq2 : Seq[String] = map.getOrElse("channel_name", Seq[String]())
val socketId = seq1.head
val channelName = seq2.head