zoukankan      html  css  js  c++  java
  • .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();
                    }
                }
  • 相关阅读:
    IOS上传图片方向问题
    在线抠图的小工具
    Notion笔记工具免费开通教育许可
    多国正在遭遇新型勒索病毒Petya侵袭
    UC 网盘:我又回来了
    数字统计
    Hello,World!
    Unity开发笔记-Timeline利用Clip实现Rewind回放
    Unity开发笔记-Timeline利用Single实现Rewind回放
    Unity开发笔记-PSD自动导出UGUI工具开发要点记录(1)PSD树形结构解析
  • 原文地址:https://www.cnblogs.com/peterYong/p/9756477.html
Copyright © 2011-2022 走看看