我正在编写一个简单的 Java http 服务器来响应 JSON 数据。我正在尝试在发送数据之前对数据进行 GZip,但它通常会发回 gzip 后的数据,从而在浏览器中产生错误。例如,在 Firefox 中它说:
内容编码错误 您尝试查看的页面无法显示,因为它使用了无效或不受支持的压缩形式。
有时,如果我正在压缩的字符串很小而没有某些字符,它会起作用,但是当有括号等时它似乎会混乱。特别是,我下面的示例文本失败了。
这是某种字符编码问题吗?我已经尝试了各种各样的东西,但它就是不想轻易工作。
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();