2

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

2 に答える 2

2

更新: これはもはや正しい答えではありません。上記の @amichair による答えを参照してください。

直感に反して、GZIPOutputStream がストリーミングに適しているとは思いません。これを試して:

...
out.println("Content-Encoding: deflate");  // NOTICE deflate encoding
out.println("Content-Type: text/html");
out.println("Connection: close");
out.println();
String x = "jsonp1330xxxxx462022184([[";
DeflaterInputStream dis = new DeflaterInputStream(out);
dis.write(x.getBytes("utf-8"));   // JSON is UTF-8
dis.close();
server.close(); //  this a bad idea, the client may not have read the data yet
于 2012-02-29T07:51:53.210 に答える