Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GZIP the response body in PlayFramework 2.0

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.

like image 921
rOrlig Avatar asked Oct 28 '12 05:10

rOrlig


1 Answers

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;
}
like image 122
Schleichardt Avatar answered Dec 01 '22 05:12

Schleichardt