GZIP the response body in PlayFramework 2.0

2019-04-29 12:20发布

问题:

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.

回答1:

gzip'ing is pretty much complete cake with an Apache front end.

On Apache 2.4 gzip handling via Location block using a basic set of content types might look like:

<Location />
  ...
  AddOutputFilterByType DEFLATE text/css application/x-javascript text/x-component text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon
  SetOutputFilter DEFLATE
</Location>


回答2:

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;
}


回答3:

In Play framework 2.2+ it is possible to use GzipFilter. Available via sbt:

libraryDependencies ++= filters

If you are a scala guy, it is worth looking at Gzip class.



回答4:

With Play 2.5, as mentioned here:

Here's a sample code to include gZip Filter(along with a sample CORS filter to showcase adding multiple filters):

import javax.inject.Inject;

import play.api.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.filters.gzip.GzipFilter;
import play.http.HttpFilters;


public class Filters implements HttpFilters {

    @Inject
    CORSFilter corsFilter;

    @Inject
    GzipFilter gzipFilter;

    @Override
    public EssentialFilter[] filters() {
        return new EssentialFilter[] { corsFilter, gzipFilter };
    }

}