公司的Spring框架接受MIME类型为json格式的带null的字符串,然后这个带null的字段被自动忽略了,排查了好久

接收方法:

解决方案:

先去掉@RequsetBody 因为使用@RequsetBody时,框架会调用HttpMessageConvert读取HttpRequest的InputStram反序列化为对象,这个InputStram只能读一次。 后续你的代码再通过Reader读输入流时,已经没有内容了,就会异常

然后用下面的方法手动去读http里面的字符串

   //这个方法不会用到公司的框架,很彻底的解决了问题
   public String getRequestString(ApiReq apiReq, HttpServletRequest request) {
        String body = "";
        try (InputStream inputStream = request.getInputStream()) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            body = outputStream.toString(request.getCharacterEncoding());
        } catch (Exception e) {
            e.printStackTrace();
            // throw new BizException("M999", "华润通知读取失败:" + e.getMessage());
        }
        return body;
    }

    //这个方法会用到公司的框架
    public String getRequestString2(ApiReq apiReq, HttpServletRequest request) {
        StringBuilder body = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                body.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
           // throw new BizException("M999", "华润通知读取失败:" + e.getMessage());
        }
        return body.toString();
    }

最后用的getRequestString方法,可以接受MIME为 json和Text 以及其他格式的字符串且不会自动忽略null

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值