/** * Compress a byte array using GZIP's default compression level. */ static byte[] gzip(byte[] data) throws IOException { return gzip(data, Deflater.DEFAULT_COMPRESSION); }
/** * Compress a byte array using GZIP's default compression level. */ static byte[] gzip(byte[] data) throws IOException { return gzip(data, Deflater.DEFAULT_COMPRESSION); }
/** * Compress the request body using the specified compression level. * The content must have already been set on the builder. */ public HttpRequestBuilder compress(int level) throws IOException { addHeader("Content-Encoding", "gzip"); entity = HttpUtils.gzip(entity, level); return this; }
/** * Compress the request body using the specified compression level. * The content must have already been set on the builder. */ public HttpRequestBuilder compress(int level) throws IOException { addHeader("Content-Encoding", "gzip"); entity = HttpUtils.gzip(entity, level); return this; }
@Test public void gzipWithLevel() throws IOException { byte[] data = "foo bar baz".getBytes(StandardCharsets.UTF_8); String result = new String(HttpUtils.gunzip(HttpUtils.gzip(data, Deflater.BEST_SPEED)), StandardCharsets.UTF_8); Assertions.assertEquals("foo bar baz", result); } }
@Test public void gzip() throws IOException { byte[] data = "foo bar baz".getBytes(StandardCharsets.UTF_8); String result = new String(HttpUtils.gunzip(HttpUtils.gzip(data)), StandardCharsets.UTF_8); Assertions.assertEquals("foo bar baz", result); }
@Test public void decompressNoChange() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8)); HttpResponse res = new HttpResponse(200, headers, entity); Assertions.assertSame(res, res.decompress()); }
@Test public void decompress() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList("application/json")); headers.put("Content-Encoding", Collections.singletonList("gzip")); byte[] entity = HttpUtils.gzip("foo bar baz foo bar baz".getBytes(StandardCharsets.UTF_8)); HttpResponse res = new HttpResponse(200, headers, entity); Assertions.assertEquals("foo bar baz foo bar baz", res.decompress().entityAsString()); Assertions.assertNull(res.decompress().header("content-encoding")); }