springboot对压缩请求的处理方法

目录
  • springboot对压缩请求的处理
  • 一、Tomcat设置压缩原理
  • 二、银联报文压缩
  • 补充:java springbooot使用gzip压缩字符串

springboot对压缩请求的处理

最近对接银联需求,为了节省带宽,需要对报文进行压缩处理。但是使用springboot自带的压缩设置不起作用:

server.compression.enabled=true
server.compression.mime-types=application/javascript,text/css,application/json,application/xml,text/html,text/xml,text/plain
server.compression.compressionMinSize=10

server.compression.enabled:表示是否开启压缩,默认开启,true:开启,false:不开启
server.compression.mime-types:压缩的内容的类型,有xml,json,html等格式
server.compression.compressionMinSize:开启压缩数据最小长度,单位为字节,默认是2048字节
源码如下:

public class Compression {
    private boolean enabled = false;
    private String[] mimeTypes = new String[]{"text/html", "text/xml", "text/plain", "text/css", "text/javascript", "application/javascript", "application/json", "application/xml"};
    private String[] excludedUserAgents = null;
    private int minResponseSize = 2048;
}

一、Tomcat设置压缩原理

tomcat压缩是对响应报文进行压缩,当请求头中存在accept-encoding时,如果Tomcat设置了压缩,则会在响应时对数据进行压缩。
tomcat压缩源码是在Http11Processor中设置的:

public class Http11Processor extends AbstractProcessor {
  private boolean useCompression() {
        // Check if browser support gzip encoding
        MessageBytes acceptEncodingMB =
            request.getMimeHeaders().getValue("accept-encoding");
        if ((acceptEncodingMB == null)-->当请求头没有这个字段是不进行压缩
            || (acceptEncodingMB.indexOf("gzip") == -1)) {
            return false;
        }
        // If force mode, always compress (test purposes only)
        if (compressionLevel == 2) {
            return true;
        }
        // Check for incompatible Browser
        if (noCompressionUserAgents != null) {
            MessageBytes userAgentValueMB =
                request.getMimeHeaders().getValue("user-agent");
            if(userAgentValueMB != null) {
                String userAgentValue = userAgentValueMB.toString();
                if (noCompressionUserAgents.matcher(userAgentValue).matches()) {
                    return false;
                }
            }
        }
        return true;
    }
}

二、银联报文压缩

作为发卡机构,银联报文请求报文是压缩的,且报文头中不存在accept-encoding字段,无法直接使用tomcat配置进行压缩解压。
需要单独处理这种请求

@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    /**
     *
     * application/xml格式报文
     * */
    @PostMapping(path = "/test", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)
    public void getUserInfoById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody;
        String resultBody="hello,wolrd";
        byte[] returnByte;
        if (StringUtils.isNoneEmpty(request.getHeader("Content-encoding"))) {
            logger.info("报文压缩,需要进行解压");
            //业务处理
            //返回报文也同样需要进行压缩处理
            assemleResponse(request,response,resultBody);
        }
    }
    public static void assemleResponse(HttpServletRequest request, HttpServletResponse response,String resultBody) throws IOException {
        response.setHeader("Content-Type","application/xml;charset=UTF-8");
        response.setHeader("Content-Encoding","gzip");
        byte[] returnByte=GzipUtil.compress(resultBody);
        OutputStream outputStream=response.getOutputStream();
        outputStream.write(returnByte);
    }
}
public class GzipUtil {
    public static String uncompress(byte[] bytes){
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String requestBody=null;
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
        GZIPInputStream gzipInputStream = null;
        try {
            gzipInputStream = new GZIPInputStream(byteArrayInputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int temp;
            while ((temp = gzipInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, temp);
            }
            requestBody = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  requestBody;
    }
    public static String uncompress(HttpServletRequest request){
        String requestBody=null;
        int length = request.getContentLength();
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(request.getInputStream());
            GZIPInputStream gzipInputStream = new GZIPInputStream(bufferedInputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int temp;
            while ((temp = gzipInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, temp);
            }
            requestBody = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  requestBody;
    }
    public static byte[] compress(String src){
        if (src == null || src.length() == 0) {
            return null;
        }
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        try {
            GZIPOutputStream gzipOutputStream=new GZIPOutputStream(byteArrayOutputStream);
            gzipOutputStream.write(src.getBytes(StandardCharsets.UTF_8));
            gzipOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes=byteArrayOutputStream.toByteArray();
        return bytes;
    }
}

补充:java springbooot使用gzip压缩字符串

import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
 * effect:压缩/解压 字符串
 */
@Slf4j
public class CompressUtils {
    /**
     * effect 使用gzip压缩字符串
     * @param str 要压缩的字符串
     * @return
     */
    public static String compress(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes());
        } catch (IOException e) {
            log.error("",e);
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (IOException e) {
                    log.error("",e);
                }
            }
        }
        return new sun.misc.BASE64Encoder().encode(out.toByteArray());
//        return str;
    }
    /**
     * effect 使用gzip解压缩
     *
     * @param str 压缩字符串
     * @return
     */
    public static String uncompress(String str) {
        if (str == null) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
        GZIPInputStream ginzip = null;
        byte[] compressed = null;
        String decompressed = null;
        try {
            compressed = new sun.misc.BASE64Decoder().decodeBuffer(str);
            in = new ByteArrayInputStream(compressed);
            ginzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = out.toString();
        } catch (IOException e) {
            log.error("",e);
        } finally {
            if (ginzip != null) {
                try {
                    ginzip.close();
                } catch (IOException e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return decompressed;
    }
}

到此这篇关于springboot对压缩请求的处理的文章就介绍到这了,更多相关springboot压缩请求内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Springboot 中的 Filter 实现超大响应 JSON 数据压缩的方法

    目录 简介 pom.xml 引入依赖 对Response进行包装 定义GzipFilter对输出进行拦截 注册 GzipFilter 拦截器 定义 Controller 定义 Springboot 引导类 测试 简介 项目中,请求时发送超大 json 数据外:响应时也有可能返回超大 json数据.上一篇实现了请求数据的 gzip 压缩.本篇通过 filter 实现对响应 json 数据的压缩.先了解一下以下两个概念: 请求头:Accept-Encoding : gzip告诉服务器,该浏览器支持

  • springboot单文件下载和多文件压缩zip下载的实现

    单文件下载 //下载单个文件 public void downloadFile(HttpServletResponse response){ String path = "D:\test\ce\1.txt" File file = new File(path); if(file.exists()){ String fileName = file.getName(); response.setHeader("Content-Disposition", "at

  • 解析SpringBoot项目开发之Gzip压缩过程

    为了减少数据在网络中的传输量,从而减少传输时长,增加用户体验,浏览器大都是支持Gzip压缩技术的,http的请求头 Accept-Encoding:gzip, deflate 就表示这次请求可以接受Gzip压缩后的数据,图片不要进行压缩,因为图片完全可以在项目开发中使用压缩后的图片.压缩会有一定的CPU性能损耗. 下面介绍几种 Gzip压缩方式 1.SpringBoot开启Gzip压缩 在application.properties中加入如下配置: server.compression.enab

  • springboot实现图片大小压缩功能

    本文实例为大家分享了springboot实现图片大小压缩的具体代码,供大家参考,具体内容如下 application.properties配置文件 #后端接收图片大小 spring.servlet.multipart.max-file-size=50MB spring.servlet.multipart.max-request-size=50MB java工具类 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jav

  • SpringBoot如何获取Get请求参数详解

    目录 前言 一.直接在请求路径中 二.参数跟在 ? 号后面 1,获取参数的基本方法 2.使用 map 来接收参数 3.接收一个集合 4.通过对象接收参数 总结 前言 利用 Spring Boot 来制作 Web 应用,就必定会涉及到前端与后台之间互相传递参数.下面演示 Controller 如何接收以 GET 方式传递过来的参数. 一.直接在请求路径中 (1).假设请求地址是如下这种 RESTful 风格,Springboot 这个参数值直接放在路径里面 http://localhost:808

  • SpringBoot记录Http请求日志的方法

    在使用Spring Boot开发 web api 的时候希望把 request,request header ,response reponse header , uri, method 等等的信息记录到我们的日志中,方便我们排查问题,也能对系统的数据做一些统计. Spring 使用了 DispatcherServlet 来拦截并分发请求,我们只要自己实现一个 DispatcherServlet 并在其中对请求和响应做处理打印到日志中即可. 我们实现一个自己的分发 Servlet ,它继承于 D

  • SpringBoot项目拦截器获取Post方法的请求body实现

    1). 存在问题流只能读取一次 2). 目标多次读取流 3). 解决方法创建包装类 4). RequestWrapper package com.mazaiting.redeye.wrapper;   import com.mazaiting.redeye.utils.StreamUtil; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory;   import jav

  • springboot接受前端请求的方法实现

    目录 普通参数 get 请求 post请求 5种不同参数类型的传递 普通参数[简单数据]:参数不同名 实体类参数 属性名里面引用别的属性名 数组参数 集合类型 错误案例 报错: 解决方法 总结 首先我们是否用的是rest风格开发的的都是适用的. 普通参数 get 请求 发送方 注:由于是get请求不用body(json)接收. 接受方 post请求 发送端 注意:在请求体(body)里面用x-www-from-urlencoded(不仅可以发请求,还可以发文件) 接受体没有 5种不同参数类型的传

  • Springboot中集成Swagger2框架的方法

    摘要:在项目开发中,往往期望做到前后端分离,也就是后端开发人员往往需要输出大量的服务接口,接口的提供方无论是是Java还是PHP等语言,往往会要花费一定的精力去写接口文档,比如A接口的地址.需要传递参数情况.返回值的JSON数据格式以及每一个字段说明.当然还要考虑HTTP请求头.请求内容等信息.随着项目的进度快速高速的迭代,后端输出的接口往往会面临修改.修复等问题,那也意味着接口文档也要进行相应的调整.接口文档的维护度以及可读性就大大下降. 既然接口文档需要花费精力去维护,还要适当的进行面对面交

  • springboot获取URL请求参数的多种方式

    1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交. /** * 1.直接把表单的参数写在Controller相应的方法的形参中 * @param username * @param password * @return */ @RequestMapping("/addUser1") public String addUser1(String username,String password) { System.out.pri

  • SpringBoot项目中使用AOP的方法

    本文介绍了SpringBoot项目中使用AOP的方法,分享给大家,具体如下: 1.概述 将通用的逻辑用AOP技术实现可以极大的简化程序的编写,例如验签.鉴权等.Spring的声明式事务也是通过AOP技术实现的. 具体的代码参照 示例项目 https://github.com/qihaiyan/springcamp/tree/master/spring-aop Spring的AOP技术主要有4个核心概念: Pointcut: 切点,用于定义哪个方法会被拦截,例如 execution(* cn.sp

  • 详解SpringBoot中异步请求和异步调用(看完这一篇就够了)

    一.SpringBoot中异步请求的使用 1.异步请求与同步请求 特点: 可以先释放容器分配给请求的线程与相关资源,减轻系统负担,释放了容器所分配线程的请求,其响应将被延后,可以在耗时处理完成(例如长时间的运算)时再对客户端进行响应.一句话:增加了服务器对客户端请求的吞吐量(实际生产上我们用的比较少,如果并发请求量很大的情况下,我们会通过nginx把请求负载到集群服务的各个节点上来分摊请求压力,当然还可以通过消息队列来做请求的缓冲). 2.异步请求的实现 方式一:Servlet方式实现异步请求

  • Spring-boot结合Shrio实现JWT的方法

    本文介绍了Spring-boot结合Shrio实现JWT的方法,分享给大家,具体如下: 关于验证大致分为两个方面: 用户登录时的验证: 用户登录后每次访问时的权限认证 主要解决方法:使用自定义的Shiro Filter 项目搭建: 这是一个spring-boot 的web项目,不了解spring-boot的项目搭建,请google. pom.mx引入相关jar包 <!-- shiro 权限管理 --> <dependency> <groupId>org.apache.s

  • SpringBoot整合Druid数据库连接池的方法

    一,Druid是什么? Druid是Java语言中最好的数据库连接池.Druid能够提供强大的监控和扩展功能. 二, 在哪里下载druid maven中央仓库: http://central.maven.org/maven2/com/alibaba/druid/ 三, 怎么获取Druid的源码 Druid是一个开源项目,源码托管在github上,源代码仓库地址是 https://github.com/alibaba/druid.同时每次Druid发布正式版本和快照的时候,都会把源码打包,你可以从

  • SpringBoot http post请求数据大小设置操作

    背景: 使用http post请求方式的接口,使用request.getParameter("XXX");的方法获取参数的值,当数据量超过几百k的时候,接口接收不到数据或者接收为null. @RequestMapping(value = "/rcv",method = RequestMethod.POST) public ResInfo<String> pullApi(HttpServletRequest request) { String channe

随机推荐