通过Request读取请求数据流中的数据 POST方式

读取方式一:通过BufferedReader,实例如下:

/**
     * 获取POST请求中Body参数-方式一字符串的方式接收
     * @param request
     * @return 字符串
     */
    public String getParm(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        String line = null;
        try {
            //接收request数据流,并指定编码格式接收
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sb.toString();
    }

方式二:IOUtils的方式

  /**
     * 获取POST请求中Body参数-方式一 二进制数组的方式接收
     * @param request
     * @return 字符串
     */
    public byte[] getParm2(HttpServletRequest request) {

        byte[] bytes = new byte[0];
        try {
            bytes = IOUtils.toByteArray(request.getInputStream());
        } catch (IOException e) {
            // TODO 异常处理可具体处理
            e.printStackTrace();
        }
        return bytes;
    }


    /**
     * 获取POST请求中Body参数-方式一 二进制数组的方式接收,然后转换成字符串
     * @param request
     * @return 字符串
     */
    public String getParm3(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        String line = null;
        byte[] bytes = new byte[0];
        try {
            bytes = IOUtils.toByteArray(request.getInputStream());
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ServletInputStream servletInputStream  = new DelegatingServletInputStream(byteArrayInputStream);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(servletInputStream));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            // TODO 异常处理可具体处理
            e.printStackTrace();
        }
        return sb.toString();
    }

说明:也可以对应JSON对象的转换,如下

 JSONObject jsonObject = JSONObject.parseObject(sb.toString());
 AccountVo accountVo1 = jsonObject.toJavaObject(AccountVo.class);
        
 AccountVo accountVo = JSONObject.parseObject(sb.toString(), AccountVo.class);

注意:
获取body参数,需要在request.getParameter()方法之前调用(如果有需要取QueryString参数的话),因为一旦调用了getParameter()方法之后,再通过IO流的方式获取body参数就失效了,会返回“”

IOUtils的详细了解可参考大牛博客:
IOUtils总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值