压缩HTTP响应时JSON被截断

时间:2011-07-04 07:51:40

标签: c# json compression deflate httplistener

当我对我的HTTP响应应用gzip或deflate压缩时,我似乎失去了我的JSON结构中的最后一个括号。例如:

结果没有压缩:

{"alist":{"P_1":0,"P_2":0,"P_3":0}}

结果 压缩浏览器:

{"alist":{"P_1":0,"P_2":0,"P_3":0}

在撰写回复而不进行压缩时,我正在执行以下操作:

byte[] buffer = Encoding.UTF8.GetBytes(responseContent);

context.Response.ContentLength64 = buffer.Length;
context.Response.ContentType = ContentTypeJson;

Stream outputStream = context.Response.OutputStream;
outputStream.Write(buffer, 0, buffer.Length);
outputStream.Close();

或者,当调用者提供Accept-Encoding请求标头时,我尝试按如下方式编写带有压缩的响应;

byte[] buffer = Encoding.UTF8.GetBytes(responseContent);
byte[] compressedBuffer;

using (var memoryStream = new MemoryStream())
{
    using (Stream compressionStream = new DeflateStream(memoryStream, CompressionMode.Compress, false))
    {
        compressionStream.Write(buffer, 0, buffer.Length);

        compressedBuffer = memoryStream.ToArray();

        compressionStream.Close();
    }

    memoryStream.Close();
}

context.Response.ContentLength64 = compressedBuffer.Length;
context.Response.ContentType = ContentTypeJson;

Stream outputStream = context.Response.OutputStream;
outputStream.Write(compressedBuffer, 0, compressedBuffer.Length);
outputStream.Close();

如果有帮助,我使用的是System.Net.HttpListener,这就是我必须自己做的原因。有没有人知道为什么会发生这种截断?

1 个答案:

答案 0 :(得分:0)

DeflateStream在写入之后不会立即写入其输出流,但您可以确定它已经 关闭它之后。所以以下内容将起作用:

compressionStream.Write(buffer, 0, buffer.Length);

compressionStream.Close();

compressedBuffer = memoryStream.ToArray();