http ContentLength 为0 下载问题
如图 通过http 下载某个东西 , WebResponse response = request.GetResponse(); response 调试如图
ContentLength 为0 但Content-Range 是有值的 导致下载的视频是0字节
修改后的代码:
public static int GetTotalSize(string url) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.CookieContainer = BaseService.CookiesContainer; WebResponse response = request.GetResponse(); int len = Int32.Parse(response.Headers["Content-Range"].ToString().Split(new char[] { '/' })[1]); return len; } public static byte[] SendRangeGetRequest(string url) { try { int len = GetTotalSize(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "get"; request.AddRange("bytes", 0, len); //这部是关键 加上它,response 的ContentLength 就有值了 if (CookiesContainer == null) { CookiesContainer = new CookieContainer(); } request.CookieContainer = CookiesContainer; //启用cookie HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream response_stream = response.GetResponseStream(); int count = (int)response.ContentLength; int offset = 0; byte[] buf = new byte[count]; while (count > 0) //读取返回数据 { int n = response_stream.Read(buf, offset, count); if (n == 0) break; count -= n; offset += n; } return buf; } catch { return null; } }
最后 File.WriteAllBytes(savePath, bytes); 就能下载到本地了