Force jersey to gzip application/json
So I’ve spent far too many hours today getting jersey to server application/json compressed with gzip. I found a number of tutorials online, followed them all. Upgraded jersey and grizzly to the newest release. Read about encoding in the jersey manuals. Enabled compression in 3 different ways. Yet still, jersey wouldn’t server the application/json resource gzipped.
The main problem was that none of the other guides specified that you had to force every response to use gzip as the encoding.
@Produces("application/json")
public Response getIt() {
return Response.ok("{'json':'yay'}")
.encoding("gzip") //forces gzip encoding
.build();
}
You can enable compression as much as you like, but if you want application/json to work, you have to force it. Change your mime type to text/plain and jersey will happily compress just about anything, but change it back to application/json again and you’re out of luck.
To enable compression in general you’ll have to add get the compression config from the listeners.
CompressionConfig compressionConfig = networkListener.getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
compressionConfig.setCompressableMimeTypes("*/*"); // the mime types to compress
}
And if we put that all together we get something like this:
resourceConfig.register(GZipEncoder.class);
HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer("UriBuilder.fromUri("http://0.0.0.0/").port(getPort(9998)).build(), resourceConfig)
for (NetworkListener networkListener : httpServer.getListeners()) {
CompressionConfig compressionConfig = networkListener.getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
compressionConfig.setCompressableMimeTypes("*/*"); // the mime types to compress
}
httpServer.start();
Comments are Disabled