How to get payload from a POST in Play 2.0

前端 未结 4 514
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 22:16

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

相关标签:
4条回答
  • 2021-02-07 22:30

    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
    
    0 讨论(0)
  • 2021-02-07 22:45

    have a look at this article on playlatam

    also check this question on google list

    for java (with a param names java_name):

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

    for scala (with a param names scala_name):

    def name = request.body.asFormUrlEncoded.get("scala_name")(0)
    
    0 讨论(0)
  • 2021-02-07 22:50

    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"))
    }
    
    0 讨论(0)
  • 2021-02-07 22:55

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

    my 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.

    0 讨论(0)
提交回复
热议问题