Gzip 是一种压缩算法,服务器经常通过这个算法来压缩响应体,再响应给客户端,从而减少数据体积,提高传输速度。客户端再通过Gzip解压缩,获取到原始的数据。因为需要压缩计算,所以会耗费额外的CPU资源。
Gzip 与 HttpHeader
对于压缩,这个行为来说,客户端与服务器都要经过协商。只有使用了同一种压缩算法,才能正确的解码出数据。http协议中定义了相关的header
Content-Encoding
是一个实体消息首部,用于对特定媒体类型的数据进行压缩。当这个首部出现的时候,它的值表示消息主体进行了何种方式的内容编码转换。这个消息首部用来告知客户端应该怎样解码才能获取在 Content-Type 中标示的媒体类型内容。
一般建议对数据尽可能地进行压缩,因此才有了这个消息首部的出现。不过对于特定类型的文件来说,比如jpeg图片文件,已经是进行过压缩的了。有时候再次进行额外的压缩无助于负载体积的减小,反而有可能会使其增大。
客户端和服务器都可以使用,表示body中的数据采用了什么编码(压缩算法)
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Encoding
Accept-Encoding
HTTP 请求头 Accept-Encoding 会将客户端能够理解的内容编码方式——通常是某种压缩算法——进行通知(给服务端)。通过内容协商的方式,服务端会选择一个客户端提议的方式,使用并在响应头 Content-Encoding 中通知客户端该选择。
即使客户端和服务器都支持相同的压缩算法,在 identity 指令可以被接受的情况下,服务器也可以选择对响应主体不进行压缩。导致这种情况出现的两种常见的情形是:
- 要发送的数据已经经过压缩,再次进行压缩不会导致被传输的数据量更小。一些图像格式的文件会存在这种情况;
- 服务器超载,无法承受压缩需求导致的计算开销。通常,如果服务器使用超过80%的计算能力,微软建议不要压缩。
只要 identity —— 表示不需要进行任何编码——没有被明确禁止使用(通过 identity;q=0 指令或是 *;q=0 而没有为 identity 明确指定权重值),则服务器禁止返回表示客户端错误的 406 Not Acceptable 响应。
一般是客户端使用,表示给服务器说明,客户端支持的压缩算法列表。服务从中选择一个对响应体进行压缩。
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Accept-Encoding
演示一个手动编/解码的Demo
服务端手动进行Gzip编码
1import java.io.ByteArrayOutputStream; 2import java.io.IOException; 3import java.nio.charset.StandardCharsets; 4import java.util.zip.GZIPOutputStream; 5 6import javax.servlet.http.HttpServletRequest; 7import javax.servlet.http.HttpServletResponse; 8 9import org.slf4j.Logger; 10import org.slf4j.LoggerFactory; 11import org.springframework.http.HttpHeaders; 12import org.springframework.http.MediaType; 13import org.springframework.web.bind.annotation.GetMapping; 14import org.springframework.web.bind.annotation.RequestMapping; 15import org.springframework.web.bind.annotation.RestController; 16 17@RestController 18@RequestMapping("/test") 19public class TestController { 20 21 private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); 22 23 @GetMapping 24 public void test(HttpServletRequest request, HttpServletResponse reponse) throws IOException { 25 26 // 响应体 27 String content = "昔日龌龊不足夸,今朝放荡思无涯。春风得意马蹄疾,一日看尽长安花。"; 28 29 String acceptEncooding = request.getHeader(HttpHeaders.ACCEPT_ENCODING); 30 31 /** 32 * 获取客户端支持的编码格式,程序可以根据这个header判断是否要对响应体进行编码 33 */ 34 LOGGER.info(acceptEncooding); 35 36 37 // 响应体使用 gzip 编码 38 reponse.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip"); 39 // 响应体类型是字符串 40 reponse.setContentType(MediaType.TEXT_PLAIN_VALUE); 41 // 编码是utf-8 42 reponse.setCharacterEncoding(StandardCharsets.UTF_8.displayName()); 43 // Gzip压缩后响应 44 reponse.getOutputStream().write(gZip(content.getBytes(StandardCharsets.UTF_8))); 45 46 } 47 48 /** 49 * Gzip压缩数据 50 * @param data 51 * @return 52 * @throws IOException 53 */ 54 public static byte[] gZip(byte[] data) throws IOException { 55 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 56 try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) { 57 gzipOutputStream.write(data); 58 gzipOutputStream.finish(); 59 return byteArrayOutputStream.toByteArray(); 60 } 61 } 62}
客户端手动解码
1import java.io.ByteArrayInputStream; 2import java.io.ByteArrayOutputStream; 3import java.io.IOException; 4import java.io.InputStream; 5import java.nio.charset.StandardCharsets; 6import java.util.zip.GZIPInputStream; 7 8import org.slf4j.Logger; 9import org.slf4j.LoggerFactory; 10import org.springframework.http.HttpEntity; 11import org.springframework.http.HttpHeaders; 12import org.springframework.http.HttpMethod; 13import org.springframework.http.MediaType; 14import org.springframework.http.ResponseEntity; 15import org.springframework.web.client.RestTemplate; 16 17public class Main { 18 19 public static final Logger LOGGER = LoggerFactory.getLogger(Main.class); 20 21 public static void main(String[] args) throws Exception { 22 23 RestTemplate restTemplate = new RestTemplate(); 24 25 26 HttpHeaders httpHeaders = new HttpHeaders(); 27 // Accept 表示客户端支持什么格式的响应体 28 httpHeaders.set(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE); 29 // Accept-Encoding 头,表示客户端接收gzip格式的压缩 30 httpHeaders.set(HttpHeaders.ACCEPT_ENCODING, "gzip"); 31 32 ResponseEntity<byte[]> responseEntity = restTemplate.exchange("http://localhost/test", HttpMethod.GET, new HttpEntity<>(httpHeaders), byte[].class); 33 34 if (!responseEntity.getStatusCode().is2xxSuccessful()) { 35 // TODO 非200响应 36 } 37 38 // 获取服务器响应体编码 39 String contentEncoding = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); 40 41 if ("gzip".equals(contentEncoding)) { // gzip编码 42 // gzip解压服务器的响应体 43 byte[] data = unGZip(new ByteArrayInputStream(responseEntity.getBody())); 44 45 LOGGER.info(new String(data, StandardCharsets.UTF_8)); 46 } else { 47 // TODO 其他的编码 48 } 49 } 50 51 /** 52 * Gzip解压缩 53 * @param inputStream 54 * @return 55 * @throws IOException 56 */ 57 public static byte[] unGZip(InputStream inputStream) throws IOException { 58 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 59 try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) { 60 byte[] buf = new byte[4096]; 61 int len = -1; 62 while ((len = gzipInputStream.read(buf, 0, buf.length)) != -1) { 63 byteArrayOutputStream.write(buf, 0, len); 64 } 65 return byteArrayOutputStream.toByteArray(); 66 } finally { 67 byteArrayOutputStream.close(); 68 } 69 } 70} 71
客户端执行日志,准确的解码了响应体
20:36:54.129 [main] INFO - 昔日龌龊不足夸,今朝放荡思无涯。春风得意马蹄疾,一日看尽长安花。
SpringBoot的响应体压缩配置
实际上,并不需要自己手动去写这种响应体的压缩代码。springboot提供了相关的配置。 SpringBoot2开启响应压缩
最后
使用RestTemplate请求文本数据接口,发现解码后的字符串是乱码。此时就可以怀疑是不是服务器响应了压缩后的数据。解决这个问题,先尝试移除Accept-Encoding请求头,告诉服务器,客户端不需要压缩响应体。如果服务器还是响应压缩后的数据,尝试读取服务器的Content-Encoding头,根据服务器的压缩编码,自己再进行解压缩。