Skip to content

Instantly share code, notes, and snippets.

@engintekin
Created October 26, 2011 20:02
Show Gist options
  • Save engintekin/1317626 to your computer and use it in GitHub Desktop.
Save engintekin/1317626 to your computer and use it in GitHub Desktop.
Gzip your response in Play framework
@With(Compress.class)
public class Application extends Controller {
public static void index() {
render();//response will be gzipped
}
}
package controllers;
import play.*;
import play.mvc.*;
import java.io.*;
import java.util.*;
import java.util.zip.GZIPOutputStream;
public class Compress extends Controller {
@Finally
public static void compress() throws IOException {
String text = response.out.toString();
// if ("text/xml".equals(response.contentType)) {
// text = new com.googlecode.htmlcompressor.compressor.XmlCompressor().compress(text);
// } else if ("text/html; charset=utf-8".equals(response.contentType)) {
// text = new com.googlecode.htmlcompressor.compressor.HtmlCompressor().compress(text);
// }
final ByteArrayOutputStream gzip = gzip(text);
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Length", gzip.size() + "");
response.out = gzip;
}
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;
}
}
@mwhawkins
Copy link

Why doesn't this work with Play 2.1.1? Is this for a different version?

@opyate
Copy link

opyate commented Dec 3, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment