【问题标题】:can not get request body with content-type=application/x-www-form-urlencoded无法使用 content-type=application/x-www-form-urlencoded 获取请求正文
【发布时间】:2013-12-05 13:50:52
【问题描述】:

当请求包含Content-Type=application/x-www-form-urlencoded时,我无法获取请求正文内容。

我有以下检索请求正文的方法:

@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST)
@ResponseBody
public String testRequestBody(@RequestBody String requestBody) {
    return requestBody;
}

我正在使用 restclient firefox 插件来测试请求。当我将Content-Type=application/x-www-form-urlencoded 添加到请求时,requestBody 变量变为空,尽管我在请求正文中有文本。当我删除 Content-Type 标头时,请求正文会填充文本。

UPD 这个问题似乎与用于运行spring容器的tomcat有关。当application/x-www-form-urlencoded请求到来时,解析,body中定义的参数成为请求参数,然后body被清除。

我可以通过以下方式访问正文参数:

@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST)
@ResponseBody
public String testRequestBody(@RequestParam("paramName") String paramName) {
    return requestParam;
}

如何配置tomcat不解析请求,不清除请求体?

【问题讨论】:

  • 我面临同样的问题。有人知道How can I configure tomcat not to parse request and not to clear request body?的答案

标签: java spring spring-mvc


【解决方案1】:

当您调用 RESTful SAS BI Web 服务时,您发送的 HTTP 标头很重要。 Content-type HTTP 标头告诉 SAS BI Web Services 您在执行 HTTP POST 时发送的内容类型。如果您正在调用 JSON 端点,那么您的 Content-type 必须设置为 application/x-www-form-urlencoded 并且您的内容必须使用这种格式进行编码。如果您正在调用 XML 端点,那么您的 Content-type 必须设置为 application/xml 并且您的内容必须是 XML。 HTTP Accept 标头告诉 SAS BI Web Services 您的客户端可以接受什么类型的内容作为输出。对于 JSON 端点,Accept 标头必须设置为 application/json,对于 XML 端点,可以将其设置为 application/xml(XML 端点不需要此标头)

@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST, headers="Accept=*")
@ResponseBody
public String testRequestBody(@RequestBody String requestBody) {
    return requestBody;
}

【讨论】:

  • 它与我的问题有什么关系?
  • 您的请求正文内容必须符合 Content-type
  • 内容对应content-type头,没有包含在requestBody变量中,就是这个问题
  • 如果对你有帮助,试试这个:@RequestMapping(value = "/testRequestBody", method = RequestMethod.POST, headers="Accept=*") @ResponseBody public String testRequestBody(@RequestBody String requestBody) {返回请求体; }
猜你喜欢
  • 2019-02-04
  • 2019-06-14
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多