GZIP encoding in Jersey 2 / Grizzly

2019-02-12 15:05发布

I can't activate gzip-encoding in my Jersey service. This is what I've tried:

  1. Started out with the jersey-quickstart-grizzly2 archetype from the Getting Started Guide.

  2. Added rc.register(org.glassfish.grizzly.http.GZipContentEncoding.class);

    (have also tried rc.register(org.glassfish.jersey.message.GZipEncoder.class);)

  3. Started with mvn exec:java

  4. Tested with curl --compressed -v -o - http://localhost:8080/myapp/myresource

The result is the following:

> GET /myapp/myresource HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 zlib/1.2.3.4 ...
> Host: localhost:8080
> Accept: */*
> Accept-Encoding: deflate, gzip
> 
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Date: Sun, 03 Nov 2013 08:07:10 GMT
< Content-Length: 7
< 
* Connection #0 to host localhost left intact
* Closing connection #0
Got it!

That is, despite Accept-Encoding: deflate, gzip in the request, there is no Content-Encoding: gzip in the response.

What am I missing here??

2条回答
Lonely孤独者°
2楼-- · 2019-02-12 15:47

You have to register the org.glassfish.jersey.server.filter.EncodingFilter as well. This example enables deflate and gzip compression:

import org.glassfish.jersey.message.DeflateEncoder;
import org.glassfish.jersey.message.GZipEncoder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.filter.EncodingFilter;
...
private void enableCompression(ResourceConfig rc) {
    rc.registerClasses(
            EncodingFilter.class,
            GZipEncoder.class,
            DeflateEncoder.class);
}

This solution is jersey specific and works not only with Grizzly, but with the JDK Http server as well.

查看更多
Viruses.
3楼-- · 2019-02-12 15:58

Try the code like:

HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(
        BASE_URI, rc, false);

CompressionConfig compressionConfig =
        httpServer.getListener("grizzly").getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON); // the mode
compressionConfig.setCompressionMinSize(1); // the min amount of bytes to compress
compressionConfig.setCompressableMimeTypes("text/plain", "text/html"); // the mime types to compress

httpServer.start();
查看更多
登录 后发表回答