获取POST参数和标题

时间:2013-10-08 03:51:40

标签: http scala playframework-2.1

我有一个RESTFul API服务,我想在POST请求中获取参数(和标题)。 http://www.playframework.com/documentation/2.1.x/ScalaRouting

没有相关信息

通过说,我有RESTFul API服务,我的意思是它没有查看页面。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

那是因为你想要的是Actions

// param is provided by the routes.
def myApiCall(param:String) = Action { request =>
  // do what you want with param
  // there are some of the methods of request:
  request.headers
  request.queryString
  Ok("") // probably there is an Ok with a better representation of empty. But it will give you a status 200 anyways...
}

有关Request

的更多信息

或者如果你只想要参数:

def myApiCall(param:String) = Action {
  //stuff with param
  Ok("...")
}

对于这两种情况,路线看起来像:

POST /myapicall/:param WhateverClass.myApiCall(param)
  • 注意:将myApiClass重命名为myApiCall,这是初衷。

答案 1 :(得分:1)

这是一个小例子:

在路线中:

GET        /user/:name     controllers.Application.getUserInfo(name)

在Application.scala

object Application extends Controller {

import play.api.libs.json._
import scala.reflect.runtime.universe._

/**
   * Generates a Json String of the parameters.
   * For example doing getJson(("status" -> "success")) returns you a Json String:
   * """
   * {
   *   "status" : "success"
   * }
   */
def getJson[T: Writes](pairs: (String, T)*): String = {
    val i = pairs.map { case (x, y) => (x -> (y: Json.JsValueWrapper)) }
    Json.obj(i: _*).toString
  }

def getUserInfo(name:String) = Action{ implicit request =>
    val user = //get User object of name
    Ok(getJson(("firstName" -> user.firstName),("lastName" -> user.lastName)))
}
//Directly calling Json.obj(("firstName" -> user.firstName),("lastName" -> user.lastName)).toString() will also do.  getJson is used to make it more readable.