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();