在 Play 中请求内容类型!REST 网络服务框架 [英] Request Content-Type in Play! Framework for REST webservices

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

问题描述

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

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, ...).

是否可以对方法进行注释以仅匹配某些内容类型(例如 @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.

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

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