C#HttpWebResponse返回编码响应

时间:2015-09-28 15:30:33

标签: c# json httpwebrequest httpwebresponse

我正在向服务器发送HttpWebRequest。这是JSON。现在,响应被编码,如下所示:

�\b\0\0\0\0\0\0��A� @ѻ�U�0l�u�\v�v�...

我可以看到我的请求在Fiddler中成功了。我可以看到服务器的响应是正确的。但是,同样在小提琴手中,它要求我先解码答案。

我不知道如何在C#中解码它。

1 个答案:

答案 0 :(得分:0)

以下是一些示例代码,它们应该完全符合您的要求。在我的情况下, BatchCollection 是我自己的对象,它映射到JSON,因此可以在解压缩后进行映射。

        var request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.Headers = headers;
        request.Headers.Add("Content-Encoding", "gzip");
        request.AutomaticDecompression = DecompressionMethods.GZip;
        request.ContentType = "application/json";

        var json = JsonConvert.SerializeObject(batchCollection);

        using (Stream requestStream = request.GetRequestStream())
        {
            var buffer = Encoding.UTF8.GetBytes(json);

            using (GZipStream compressionStream = new GZipStream(requestStream, CompressionMode.Compress, true))
            {
                compressionStream.Write(buffer, 0, buffer.Length);
            }
        }

        var response = (HttpWebResponse)request.GetResponse();
        BatchCollection batchOut = null;

        using (Stream responseStream = response.GetResponseStream())
        {
            var reader = new StreamReader(responseStream);
            var jsonOut = reader.ReadToEnd();
            reader.Close();
            batchOut = JsonConvert.DeserializeObject<BatchCollection>(jsonOut);
        }

        return batchOut;