【问题标题】:Grails Form POST with missing params when form Content-Type = text当表单 Content-Type = text 时,Grails Form POST 缺少参数
【发布时间】:2015-03-14 22:06:12
【问题描述】:

我有一个第三方应用程序发布数据的控制器操作, 问题是 POST 请求参数为空,这是由于 POST Content-Type = 'text'。 如果我使用 Content-Type = 'application/x-www-form-urlencoded' 模拟(使用 Chrome Rest Console 插件)相同的 POST 那么请求参数就被正确填写了。

如何启用 Content-Type = 'text' 的 POST 数据?

【问题讨论】:

  • 这样做有什么理由吗?告诉他们向您发送正式的发帖请求。
  • 很遗憾不能更改 POST 请求

标签: grails post controller content-type


【解决方案1】:

您可以使用访问原始 POST 数据

request.reader.text

据我所知(我可能错了)grails 不会解析这种内容类型,因为它最终使用HTTPServletRequest,它只解析www-form-urlencoded,因为这是传递变量值的正常方式通过 HTTP。

您可以使用 grails 过滤器轻松模拟您想要的行为,例如:

class TextRequestFilters {
    def filters= {
        textRequestFilter(controller: '*', action:'*') {
            before = {
                if(request.post && request.format == 'text') {
                    String postBody = request.reader.text
                    String[] variables = postBody.split('&')
                    variables.each { String variable ->
                        String[] parts = variable.split('=')
                        String key = URLDecoder.decode(parts[0], request.characterEncoding)
                        String value = URLDecoder.decode(parts[1], request.characterEncoding)
                        params[key] = value
                    }
                }
            }
        }
    }
}

注意事项:

您可能希望从此过滤器中排除资产请求等。

内容类型应该是 text/plain,因为这是 grails 直接转换为文本格式的内容,但我相信您可以在 Config.groovy 中进行设置。

【讨论】:

  • 我想知道是否有办法像普通 POST 一样填充参数以避免解析 request.reader.text
  • 我已经更新了我的答案,以描述一种更舒适的使用方式。
猜你喜欢
  • 2013-11-21
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
相关资源
最近更新 更多