HttpServletRequest如何获取body内容(字符串/二进制)呢?
下文笔者讲述HttpServletRequest获取body内容的方法分享,如下所示:
获取HTTP字符串body
String getBodytxt(HttpServletRequest request) { BufferedReader br = request.getReader(); String str, wholeStr = ""; while((str = br.readLine()) != null){ wholeStr += str; } return wholeStr; }
获取HTTP二进制body
private String getBodyData(HttpServletRequest request) { StringBuffer data = new StringBuffer(); String line = null; BufferedReader reader = null; try { reader = request.getReader(); while (null != (line = reader.readLine())) data.append(line); } catch (IOException e) { } finally { } return data.toString(); }
使用注解的方式获取body内容
@RequestBody获取body @RequestMapping(value = "/testurl", method = RequestMethod.POST) @ResponseBody public ServiceResult TestUrl(HttpServletRequest request, @RequestBody JSONObject jsonObject){ String username = jsonObject.get("username").toString(); String pwd = jsonObject.get("pwd").toString(); } @RequestBody 可以使用JSONObject, Map ,或者ObjectDTO绑定body。 @RequestParam获取body @RequestMapping(value = "/testurl", method = RequestMethod.POST) @ResponseBody public ServiceResult TestUrl(HttpServletRequest request,@RequestParam("username")String username, @RequestParam("pwd")String pwd) { String txt = username + pwd; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。