当前位置: 代码迷 >> 综合 >> HttpServletRequest获取body 使用 @RequestBody 获取body
  详细解决方案

HttpServletRequest获取body 使用 @RequestBody 获取body

热度:100   发布时间:2023-10-10 00:04:36.0

直接从HttpServletRequest的Reader流中获取请求body参数

	@RequestMapping(value = "/nty=", method = RequestMethod.POST)public JSONObject ForwardNtyMsg(HttpServletRequest request) throws IOException {
    // 直接从HttpServletRequest的Reader流中获取RequestBodyBufferedReader reader = request.getReader();StringBuilder builder = new StringBuilder();String line = reader.readLine();while(line != null){
    builder.append(line);line = reader.readLine();}reader.close();String reqBody = builder.toString();System.out.println("recv json data:" + reqBody);// string 2 jsonobjectJSONObject json = JSONObject.parseObject(reqBody);System.out.println("recv ntydel from:" + request.getRequestURI());// todo..// returnJSONObject retjson = new JSONObject();retjson.put("recv", "success");return retjson;}

使用 @RequestBody 获取body

	@RequestMapping(value = "/nty", method = RequestMethod.POST)public JSONObject ForwardNtyMsg(@RequestBody JSONObject jsonString, HttpServletRequest httpServletRequest) {
    System.out.println("recv nty json data:" + jsonString.toJSONString());System.out.println("recv nty from:" + httpServletRequest.getRequestURI());// todo..// returnJSONObject json = new JSONObject();json.put("recv", "success");return json;}
  相关解决方案