You shouldn't randomly gzip responses. You can only gzip the response when the client has notified the server that it accepts (understands) gzipped responses. You can do that by determining if the Accept-Encoding
request header contains gzip
. If it is there, then you can safely wrap the OutputStream
of the response in a GZIPOutputStream
. You only need to add the Content-Encoding
header beforehand with a value of gzip
to inform the client what encoding the content is been sent in, so that the client knows that it needs to ungzip it.
In a nut:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
OutputStream output = null;
String acceptEncoding = request.getHeader("Accept-Encoding");
if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
response.setHeader("Content-Encoding", "gzip");
output = new GZIPOutputStream(response.getOutputStream());
} else {
output = response.getOutputStream();
}
output.write(json.getBytes("UTF-8"));
(note that you would like to set the content type and character encoding as well)
You could also configure this at appserver level. Since it's unclear which one you're using, here's just a Tomcat-targeted example: check the compression
and compressableMimeType
attributes of the <Connector>
element in /conf/server.xml
: HTTP connector reference. This way you can just write to the response without worrying about gzipping it.