簡體   English   中英

WebRequest.AddRange 沒有返回正確的 Content-Length

[英]WebRequest.AddRange doesn't return the correct Content-Length

我想部分下載 url 中的文件。 但它返回錯誤的內容大小,我不知道為什么。 遠程文件有Accept-Ranges=bytes怎么解決?

long start = 536871935, end = 805306878;
string url = "http://ipv4.download.thinkbroadband.com/1GB.zip";

var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362";
request.AllowAutoRedirect = true;
request.Method = "GET";
request.Timeout = 5000;
request.ReadWriteTimeout = 3000;
request.AddRange(start, end);

var response = (HttpWebResponse)request.GetResponse();
if (response.ContentLength != end - start + 1)
    throw new Exception(string.Format("Returned content size is wrong; start={0}, end={1}, returned = {2}, shouldbe = {3}",
            start, end, response.ContentLength, end - start + 1));
        

Downloadmanager.exe 中出現“System.Exception”類型的異常,但未在用戶代碼中處理

附加信息:返回的內容大小錯誤 start=536871935,end=805306878,返回=536869889,應該=268434944

我正在使用HttpClient而不是HttpWebRequest (微軟推薦)並且沒有這樣的問題。

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        long start = 536871935, end = 805306878;
        try
        {
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://ipv4.download.thinkbroadband.com/1GB.zip"))
            {
                request.Headers.Range = new RangeHeaderValue(start, end);
                using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();
                    Console.WriteLine(response.Content.Headers.ContentLength);
                    Console.WriteLine(end - start + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }
}

控制台 output

268434944
268434944

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM