泽西,内容gzip / deflate

时间:2013-09-26 05:13:22

标签: jersey jersey-2.0

我正在尝试理解如何根据Content-Encoding gzip | deflate应用不同的拦截器并根据Accept-Encoding提供数据。我正在阅读有关gzip / deflate拦截器的内容,但不太明白它是如何工作的。

public Response bigPayload( PayloadDto data ) {
   ...
   return Response.ok( BigDataDto ).build(); 
}

基本上我希望能够接受有效载荷json的gzip / deflate并返回gzip / deflate数据(如果支持)。

谢谢。

2 个答案:

答案 0 :(得分:2)

要在服务器端使用GZIP和Jersey,首先应该实现ReaderInterceptor和WriterInterceptor:

@Provider // This Annotation is IMPORTANT!
public class GZipInterceptor implements ReaderInterceptor, WriterInterceptor {
    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
        List<String> header = context.getHeaders().get("Content-Encoding");
        // decompress gzip stream only
        if (header != null && header.contains("gzip")) 
            context.setInputStream(new GZIPInputStream(context.getInputStream()));
        return context.proceed();
    }

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        context.setOutputStream(new GZIPOutputStream(context.getOutputStream()));
        context.getHeaders().add("Content-Encoding", "gzip");
        context.proceed();
    }
}

然后确保这个@Provider类位于由web.xml配置的自动扫描包/子包中:

<servlet>
    <servlet-name>Jersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>your.provider.package</param-value>
    </init-param>
</servlet>

如果你想按需使用gzip压缩,可能你可以使用ThreadLocal变量寻求帮助,详情请查看我的帖子here

答案 1 :(得分:0)

我希望在设置标头Accept-Encoding: gzip, deflate时从用户请求返回压缩响应,然后您需要在应用程序服务器中启用压缩。

在Tomcat中,您需要更改<TOMCAT_HOME>/conf/server.xml,因为默认情况下压缩已关闭。

    <Connector connectionTimeout="20000" 
            port="8080" protocol="HTTP/1.1" 
            redirectPort="8443" 
            compression="on"
            compressionMinSize="1"
            noCompressionUserAgents="gozilla, traviata"
            compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain"/>

请注意,您需要定义您希望应用服务器压缩的compressableMimeType。

然后你可以用卷发来测试....

未压缩的内容......

curl http://localhost:8080/your/url/too/data

压缩内容......

curl -H "Accept-Encoding: gzip, deflate" http://localhost:8080/your/url/too/data