GZIP PlayFramework 2.0 中的响应正文

2024-02-03

我正在开发 Playframework 2.x 应用程序。我的应用程序中的控制器将 JSON 响应返回到浏览器/端点。我想知道是否有一种简单的方法来启用响应正文的 GZIP 压缩。


目前在 2.0.4 版本中,对于非资产没有简单的方法。

对于 Java API,您可以使用:

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GZIP PlayFramework 2.0 中的响应正文 的相关文章

随机推荐