将HttpWebRequest.AutomaticDecompression设置为gzip后,响应的ContentLength属性返回-1。 (在你说之前,是的,有响应内容!)这是一个很大的问题,因为我不能用我需要从响应流中读取的字节数来创建我的字节数组。
我分析了Fiddler中的响应,ContentLength属性是正确的,.NET似乎并不想使用它。
如果未设置AutomaticDecompression属性,则响应ContentLength将返回正的预期值。
我想利用内置的减压功能。任何想法为什么会发生这种情况?
我的代码:
var request = (HttpWebRequest)WebRequest.Create(URI);
request.ReadWriteTimeout = 300000;
request.Timeout = 300000;
request.ImpersonationLevel = TokenImpersonationLevel.Anonymous;
request.Method = RequestMethod;
if (RequestDetails.GzipCompress) request.Headers.Add("Accept-Encoding", "gzip");
request.Accept = RequestDetails.Accept;
request.ContentType = RequestDetails.ContentType;
request.KeepAlive = RequestDetails.KeepAlive;
request.ServicePoint.Expect100Continue = false;
request.UserAgent = "UA";
request.CookieContainer = null;
request.Proxy = null;
request.AutomaticDecompression = DecompressionMethods.GZip;
if (RequestDetails.CustomHeaders != null) foreach (var pair in RequestDetails.CustomHeaders) request.Headers.Add(pair.Key, pair.Value);
if (RequestData != null && RequestData.Length > 0)
{
request.ContentLength = RequestData.Length;
using (var ps = request.GetRequestStream())
{
ps.Write(RequestData, 0, RequestData.Length);
}
}
HttpWebResponse response;
try { response = (HttpWebResponse)request.GetResponse(); }
catch (WebException ex) { response = (HttpWebResponse)ex.Response; }
if (!request.HaveResponse || response == null) throw new Exception("No response! The operation may have timed out.");
byte[] responseData = null;
if (response.ContentLength > 0) //-1!!!
答案 0 :(得分:1)
固定。不得不做回应.Headers [HttpResponseHeader.ContentLength]。
请注意,这是COMPRESSED数据的大小。幸运的是,在我的情况下,我连接的服务器发回一个HTTP头,其中包含解压缩内容长度的大小。如果你没有,我想读取所有数据的唯一方法是声明一个静态的大型缓冲区,并读取响应流,直到它返回0字节读取。