I am working on Playframework 2.x application. The controllers in my application return JSON response back to the browser/endpoint. I wanted to know if there is a simple way to enable GZIP compression of the response bodies.
Currently in play 2.0.4 there is no simple way for non assets.
For the Java API you could use:
public static Result actionWithGzippedJsonResult() throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put("hello", "world");
final String json = Json.toJson(map).toString();
return gzippedOk(json).as("application/json");
}
/** Creates a response with a gzipped string. Does NOT change the content-type. */
public static Results.Status gzippedOk(final String body) throws IOException {
final ByteArrayOutputStream gzip = gzip(body);
response().setHeader("Content-Encoding", "gzip");
response().setHeader("Content-Length", gzip.size() + "");
return ok(gzip.toByteArray());
}
//solution from James Ward for Play 1 and every request: https://gist.github.com/1317626
public static ByteArrayOutputStream gzip(final String input)
throws IOException {
final InputStream inputStream = new ByteArrayInputStream(input.getBytes());
final ByteArrayOutputStream stringOutputStream = new ByteArrayOutputStream((int) (input.length() * 0.75));
final OutputStream gzipOutputStream = new GZIPOutputStream(stringOutputStream);
final byte[] buf = new byte[5000];
int len;
while ((len = inputStream.read(buf)) > 0) {
gzipOutputStream.write(buf, 0, len);
}
inputStream.close();
gzipOutputStream.close();
return stringOutputStream;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With