GZIP encoding in Jersey 2 / Grizzly

浪子不回头ぞ 提交于 2019-11-27 18:00:45

问题


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??


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/19751014/gzip-encoding-in-jersey-2-grizzly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!