【问题标题】:How does Grails' content negotiation handle opposing types?Grails 的内容协商如何处理对立的类型?
【发布时间】:2011-12-08 19:42:17
【问题描述】:

Grails supports content negotiation 来自 3 个不同的来源:

  1. 接受标头
  2. 请求参数(格式)
  3. URI 扩展

问题是,当它从多个地方获取内容信息时,尤其是当它们彼此不一致时,它会做什么?

例如,如果 Grails 收到如下请求会发生什么:

URL: http://example.com/book/list.html?format=json
Accept: application/xml

Accept 标头将解析为 xml,URI 扩展将解析为 html,而参数将解析为 json。

这会做什么:

import grails.converters.*

class BookController {

    def list() {
        def books = Book.list()
        withFormat {
            html bookList: books
            xml { render books as XML }
            json { render books as JSON }
        }
    }
}

【问题讨论】:

    标签: rest grails content-type content-negotiation


    【解决方案1】:

    对于 Grails 2.0.0RC3,以下将返回 html 块。

    curl -v -H "Accept: application/xml" http://localhost:8080/book/book/list.html?format=json
    

    优先顺序为:

    1. URI 扩展
    2. 格式请求参数
    3. 接受标头

    请注意,为了使用 Accept 标头,您必须更改 grails-app/conf/Config.groovy 文件中的以下参数(默认为 false):

    grails.mime.use.accept.header = true
    

    【讨论】:

      猜你喜欢
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2014-11-15
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多