请求播放中的内容类型! REST Web服务框架 [英] Request Content-Type in Play! Framework for REST webservices

查看:111
本文介绍了请求播放中的内容类型! REST Web服务框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Play实施REST网络服务!框架.我知道如何通过指定多个模板以不同的格式(JSON,XML,HTML等)返回响应.但是,我找不到有关如何处理(例如POST)请求(表单编码,JSON,XML等)中的不同Content-Type的任何信息.

I'm trying to implement a REST webservice with the Play! framework. I know how I can return a response in different formats (JSON, XML, HTML, ...) by specifying multiple templates. However, I didn't find any information on how you should process different Content-Types in a (e.g. POST) request (form encoded, JSON, XML, ...).

是否可以注释一种方法以仅匹配某些Content-Type(类似于@Consumes)?我必须在控制器方法中使用if子句来区分不同的请求内容类型吗?

Is it possible to annotate a method to match only certain Content-Types (something like @Consumes)? Do I have to differentiate between the different request Content-Types with an if-clause in the controller method?

推荐答案

看看结合了正文解析器的Play文档:

Have a look at the Play documentation for combining body parsers:

http://www.playframework.com/documentation/2.2.0/ScalaBodyParsers

如果您想将帖子正文限制为仅xml或json,则可以按照以下方式编写内容:

If you want to constrain a post body to only xml or json you can write something along these lines:

val xmlOrJson = parse.using {
  request =>
    request.contentType.map(_.toLowerCase(Locale.ENGLISH)) match {
      case Some("application/json") | Some("text/json") => play.api.mvc.BodyParsers.parse.json
      case Some("application/xml") | Some("text/xml") => play.api.mvc.BodyParsers.parse.xml
      case _ => play.api.mvc.BodyParsers.parse.error(Future.successful(UnsupportedMediaType("Invalid content type specified")))
    }
}

def test = Action(xmlOrJson) {
  request =>
    request.body match {
      case json: JsObject => Ok(json) //echo back posted json
      case xml: NodeSeq => Ok(xml) //echo back posted XML
    }
}

xmlOrJson函数查看内容类型请求标头以确定主体解析器.如果它不是xml或json,则它将返回带有UnsupportedMediaType响应(HTTP 415)的错误正文解析器.

The xmlOrJson function looks at the content type request header to determine the body parser. If it is not xml or json then it returns the error body parser with an UnsupportedMediaType response (HTTP 415).

然后,您将此函数作为要限制为xml或json内容的任何动作的主体解析器传入.在操作中,您可以查看正文以确定是否已解析xml或json并进行相应处理.

You then pass this function in as the body parser of any action you want to constrain to xml or json content. Within the action you can look at the body to determine if xml or json was parsed and process accordingly.

这篇关于请求播放中的内容类型! REST Web服务框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆