.NET程序下載獲得的ContentLength=-1


你寫的.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();
                }
            }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM