How can my Play 2 app respond to different “Accept” headers from the client?

后端 未结 2 1149
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 23:42

In Rails, I was able to do something similar to the following:

respond_to do |format|
  format.xml { ... }
  format.json { ... }
end

and the ap

2条回答
  •  醉酒成梦
    2021-02-06 00:21

    In Play 2.1 you can write the following:

    request match {
      case Accepts.Xml() => Ok({e.message})
      case Accepts.Json() => Ok(…)
    }
    

    The cases statements are tried in the order they are written, so if your client sets the HTTP Accept header to */* the first one will match (in this example case Accepts.Xml()). So, you usually want to write the Accepts.Html() case first because browsers set the Accept header to */*.

    (Note: you may also be interested in this answer for a similar question in Java)

提交回复
热议问题