欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpServletRequest中读取HTTP请求的body

程序员文章站 2024-02-04 20:01:40
...

背景

Spring MVC 等框架用久了之后,发现对于POST请求里面如果不使用@RequestBody 好像很难获得POST的body。

HTTP请求中的是字符串数据

字符串读取

void charReader(HttpServletRequest request) {
    BufferedReader br = request.getReader();

    String str, wholeStr = "";
    while((str = br.readLine()) != null){
        wholeStr += str;
}
System.out.println(wholeStr);

}

二进制读取

void binaryReader(HttpServletRequest request) {
        int len = request.getContentLength();
        ServletInputStream iii = request.getInputStream();
        byte[] buffer = new byte[len];
        iii.read(buffer, 0, len);
}

@RequestBody

@RequestMapping(value = "/feedback", method = RequestMethod.POST)
    @ResponseBody
    public ServiceResult feedbackEmail(HttpServletRequest request,
        @RequestBody JSONObject jsonObject
                               ){

       String emailTitle =  jsonObject.get("emailTitle").toString();
       String emailBody = jsonObject.get("emailBody").toString();
}

@RequestBody 可以使用JSONObject, Map ,或者ObjectDTO绑定body。
或者使用

@RequestParam

@RequestMapping(value = "/email", method = RequestMethod.POST)
@ResponseBodypublic ServiceResult Email(HttpServletRequest request,

@RequestParam("emailTitle")String emailTitle,

@RequestParam("emailBody")String emailBody)  {



  BufferedReader br = request.getReader();


    while((str1 = br.readLine()) != null) {

    wholeStr += str1;

}

注意

request.getInputStream(); request.getReader();和request.getParameter(“key”);这三个函数中任何一个函数执行一次后(可正常读取body数据),之后再执行就无效了。

参考:
http://blog.csdn.net/zxygww/article/details/47045055(body数据读取)
http://blog.csdn.net/xkhgnc_6666/article/details/51767838(post请求中参数为json格式)