java web 接收application/json的post请求数据

接收前端或第三方推送的Post请求数据时,通常利用request获取参数可以直接通过request.getParameter("name")的方式获取URL上或者ajax data提交上来的参数。但是body是没有名字的,无法通过参数名字这种方式获取。

两个方法:

方法一:通过@RequestBody进行获取请求中的body内容,注意:通过实体类的方式接收必须使上传的参数名称与实体类中的属性名称一致。

1
2
3
public ReturnT addAutomaticOperationTactics(HttpServletRequest request, @RequestBody User user) throws Exception {
        return ReturnT.SUCCESS;
    }

 

方法二:通过IO流的方式提取body中的数据

1
import com.alibaba.fastjson.JSONObject;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ReturnT<Object> disciplineViolation(HttpServletRequest request) throws Exception{
       try {
           BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
           StringBuilder responseStrBuilder = new StringBuilder();
           String inputStr;
           while ((inputStr = streamReader.readLine()) != null){
               responseStrBuilder.append(inputStr);
           }
           JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
           String stuNo = jsonObject.getString("stuNo");
           return objectReturnT;
       } catch (Exception e) {
           e.printStackTrace();
           throw new Exception(e.getMessage());
       }
   }

 

作者:假装空白
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

posted @   假装空白  阅读(3122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示