JSON データで応答する単純な Java http サーバーを作成しています。データを送信する前に 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();