首页 > Spring MVC处理POST请求时无法获得RequestBody数据

Spring MVC处理POST请求时无法获得RequestBody数据

  1. 使用python发出post请求, Spring无法获得纯净的requestBody数据.

  2. 请求代码:

#!/usr/bin/python

import urllib2,urlparse

def httppost(host, action, data):
    url = urlparse.urljoin(host, action)
    print(url)
    return urllib2.urlopen(url, data).read()

def httppost_(host, action, data):
    opener = urllib2.build_opener()
    request = urllib2.Request(host+action, data, headers={"Content-Type": "text/plain"})
    return opener.open(request).read()

if __name__ == "__main__":
    print httppost("http://localhost:8086", "/xxx?name1=v1&name2=v2", "bodydata")
    print httppost_("http://localhost:8086", "/xxx?name1=v1&name2=v2", "bodydata")

后台处理代码:

   @RequestMapping(value="/xxx", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Object saveVdmpConfig(@RequestParam int vdmpid,
                                 @RequestParam String module,
                                 @RequestParam String file,
                                 @RequestBody String requestBody,
                                 HttpServletResponse response,
                                 HttpServletRequest request) throws IOException {

        logger.debug(requestBody);
        FishboneResult frt;
        frt = (FishboneResult) configService.setVdmpConfig(vdmpid, module, file, requestBody);
        response.setStatus(frt.getRet());
        return frt;
    }

3.那么requestBody的打印信息为:
//application/x-www-form-urlencoded格式post
name1=v1&name2=v2&bodydata=
// text/plain格式post
bodydata

然而在python的tornado框架中的tornado.httputil.HTTPServerRequest对象中却可以获得bodydata,
用tornado.httputil.HTTPServerRequest.body得到bodydata数据, 对这两种请求都能得到一样的结果:bodydata.后台处理代码如下:

             def post(self):
                 # in vdmp mode, we must have a vdmpid
                 vdmpid = self.get_argument("vdmpid")
                 module = self.get_argument("module")
                 fname = self.get_argument("file")
                 fvalue = self.request.body
                 logger.debug(self.request.body)
                 self.dopost(vdmpid, module, fname, fvalue)

然而在SpringMVC中的HttpServletRequest对象中却获得不到纯净的bodydata数据, 也就是直接获得bodydata

虽然可以修改请求方式解决这一问题,不过请求的位置需要统计,修改量比较大.所以最好能够在后台处理.
当然可以通过HttpServletRequest的getContentType方法获得post请求类型,然后分别处理之,不过有没有更优雅的办法呢?


为何不考虑使用requests取发包呢?

【热门文章】
【热门文章】