javagziphttprequestcompressiongzipoutputstream

GZIPOutputStream not properly compressing a String for HTTP Response


I'm writing a simple Java http server that responds with JSON data. I'm trying to GZip the data before sending it, but it usually sends back gzipped data that produces an error in the browser. For example, in Firefox it says:

Content Encoding Error The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

Sometimes it works if the string I'm compressing is small without certain characters, but it seems to mess up when there are brackets, etc. In particular, the example text I have below fails.

Is this some kind of character encoding issue? I've tried all sorts of things, but it just doesn't want to work easily.

String text;            
private Socket server;
DataInputStream in = new DataInputStream(server.getInputStream());
PrintStream out = new PrintStream(server.getOutputStream());

while ((text = in.readLine()) != null) {
    // ... process header info
    if (text.length() == 0) break;
}

out.println("HTTP/1.1 200 OK");
out.println("Content-Encoding: gzip");
out.println("Content-Type: text/html");
out.println("Connection: close");


// x is the text to compress
String x = "jsonp1330xxxxx462022184([[";
ByteArrayOutputStream outZip = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outZip);

byte[] b = x.getBytes(); // Changing character encodings here makes no difference

gzip.write(b);
gzip.finish();
gzip.close();
outZip.close();
out.println();
out.print(outZip);
server.close();

Solution

  • The accepted answer is incorrect.

    GZIPOutputStream can indeed be used to implement gzip content encoding in HTTP. In fact, that's exactly how I implemented it in the JLHTTP lightweight HTTP server. Support for deflate content encoding is identical, just with DeflaterOutputStream used instead. The problem with the above code is simply that it's buggy :-)

    With the code fixed, GZIPOutputStream works like a charm.

    However, while great for educational purposes, please note that this is not an HTTP server, even if fixed. You could further read RFC 2616 or 7230 to learn what else HTTP is required to do... but why reinvent the weel? There are a bunch of lightweight embeddable HTTP servers out there that you can use to get the job done properly with little effort, JLHTTP among them.