Java gzip压缩数据传送、模拟请求后端

先说一说背景,因为接口请求传入的数据量太多太大,导致需要使用Gzip压缩数据然后再传送给接口,数据压缩的方式来减少传输的数据量,从而提高传输效率。

gzip故事会

      Gzip是若干种文件压缩程序的简称,通常指GNU计划的实现,此处的gzip代表GNU zip。也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。在1992年10月31日第一次公开发布,版本号0.1,1993年2月,发布了1.0版本。

       GZIP最早由Jean-loup Gailly和Mark Adler创建,用于UNⅨ系统的文件压缩。我们在Linux中经常会用到后缀为.gz的文件,它们就是GZIP格式的。现今已经成为Internet 上使用非常普遍的一种数据压缩格式,或者说一种文件格式。

         HTTP协议上的GZIP编码是一种用来改进WEB应用程序性能的技术。大流量的WEB站点常常使用GZIP压缩技术来让用户感受更快的速度。这一般是指WWW服务器中安装的一个功能,当有人来访问这个服务器中的网站时,服务器中的这个功能就将网页内容压缩后传输到来访的电脑浏览器中显示出来.一般对纯文本内容可压缩到原大小的40%.这样传输就快了,效果就是你点击网址后会很快的显示出来.当然这也会增加服务器的负载. 一般服务器中都安装有这个功能模块的。

程序

接口请求格式:HttpServletRequest

 @RequestMapping(value = "/power/route_plan/around", method = {RequestMethod.POST})
    public Object powerEnergySearchAlongtheWay(HttpServletRequest request) {
        PowerResourceALongWayParam param = gzipToParam(request);
        return energyMapResultReturnService.scheduleByRouteRound(param);
    }

解压方法

这里注意请求时需要带下面参数,这样代码识别时知道是gzip传输

private PowerResourceALongWayParam gzipToParam (HttpServletRequest request) {
        PowerResourceALongWayParam param = null;
        String contentEncoding = request.getHeader("Content-Encoding");
        if (null != contentEncoding && contentEncoding.contains("gzip")) {
            try (ServletInputStream inputStream = request.getInputStream()) {
                if (inputStream != null) {
                    try (BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(inputStream)))) {
                        StringBuffer sb = new StringBuffer("");
                        String temp;
                        while ((temp = br.readLine()) != null) {
                            sb.append(temp);
                        }
                        br.close();
                        String acceptjson = sb.toString();
                        System.out.println("解压之后字符串为:" + acceptjson);
                        param = MapperUtils.deserialize(acceptjson, PowerResourceALongWayParam.class);
                    }
                }
            } catch (IOException e) {
                log.info("转换 gzip 数据 为 param 报错, ", e);
                throw new ResponseRuntimeException(ResultCode.REQUEST_DATA_INVALID, "request 输入 gzip 数据格式有误. ");
            }
        } else {
            throw new ResponseRuntimeException(ResultCode.REQUEST_DATA_INVALID, "request header Content-Encoding 应该包含 gzip. ");
        }

        Preconditions.checkState(param != null, "param 输入有误");

        return param;
    }

模拟请求

public static void main(String[] args) {

        FileInputStream fileInputStream = null;

        try {

            File file = new File("/data/test.txt");
            byte[] bFile = new byte[(int) file.length()];
            
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bFile);
            
            byte[] bytes = Gzip(bFile);
            writeRtreeResourceEntity2FileString(bytes,"test1.txt");
            System.out.println("OK");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    /**
     * gzip压缩
     */
    public static byte[] Gzip(byte[] data) {
        byte[] b = null;
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(data);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            byte[] buffer = new byte[4096];
            int n = 0;
            while((n = in.read(buffer, 0, buffer.length)) > 0){
                gzip.write(buffer, 0, n);
            }
            gzip.close();
            in.close();
            b = out.toByteArray();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return b;
    }
    /**
     * 写入文件中
     */
public static void writeRtreeResourceEntity2FileString(byte[] bFile, String text) {
        String outPutStreamFilePath = "/data/" + text;
        OutputStream outPutStream = null;
        try {
            File file = new File(outPutStreamFilePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            outPutStream = new FileOutputStream(file, false);
            outPutStream.write(bFile);
            /*for (Map.Entry<String, String> entry : map.entrySet()) {
                StringBuilder data = new StringBuilder();
                data.append(entry.getKey()).append(":").append(entry.getValue());
                outPutStream.write(data.toString().getBytes());
                outPutStream.write("\n".getBytes());
            }*/
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outPutStream != null) {
                try {
                    outPutStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

而test.txt中数据就是postman中请求的json,而我们需要gzip压缩为二进制流传递到接口

最后postman请求就可以了

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值