码迷,mamicode.com
首页 > Web开发 > 详细

.NET程序下载获得的ContentLength=-1

时间:2018-10-08 20:47:25      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:res   request   div   内容   length   cep   buffer   man   ons   

你写的.NET(C#)下载程序是否会遇到过这样的问题?--ContentLength=-1.

例如,有如下代码:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

HttpWebResponse webResponse = null;

webRequest.Timeout = 100000;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream resStream = webResponse.GetResponseStream();

StreamReader xtReader = new StreamReader(resStream);
int DataSize = webResponse.ContentLength;//ContentLength 等于-1

会发现ContentLength=-1,这是为什么呢?!

用http分析工具会发现,原因原来是很简单的,这是因为某些网站服务器在发送响应内容时,会用gzip或 deflate等压缩算法压缩网页的内容,这样能使网页内容的数据包体积大大减小,从而加快了网络传输,这样客户端的浏览器显示网页也加快了。就是因为这 个gzip或 deflate功能,使得网页数据在进行http传输时不会在header里加上ContentLength属性,所以程序取回 来的ContentLength 的数值就默认为-1了(而 没有gzip或 deflate功能的网页肯定会ContentLength具体数值)

改进:

byte[] arraryByte = new byte[1024];
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(filePath);
                req.Method = "Get";
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;
                ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true;
                using (HttpWebResponse wr = (HttpWebResponse)req.GetResponse())
                {
                    Stream stream = wr.GetResponseStream();
                    //读取到内存
                    MemoryStream stmMemory = new MemoryStream();
                    byte[] buffer1 = new byte[1024 * 100];  //每次从文件读取1024个字节。
                    int i;
                    //将字节逐个放入到Byte 中
                    while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0)
                    {
                        stmMemory.Write(buffer1, 0, i);
                    }
                    arraryByte = stmMemory.ToArray();
                    stmMemory.Close();
                    stream.Close();
                }
            }

 

.NET程序下载获得的ContentLength=-1

标签:res   request   div   内容   length   cep   buffer   man   ons   

原文地址:https://www.cnblogs.com/peterYong/p/9756477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!