HttpWebResponse 对于 ContentLength 是错误的

HttpWebResponse is wrong for the ContentLength

我有HTTP协议的下载方法。但它似乎无法正常工作,出了点问题。我用一些 url 来源对其进行了测试,除了最后一个之外,它都是正确的。 ContentLength 属性 对于 url 是错误的。它在运行时显示为 210 kb,但实际上是 8 MB。我将通过分享我的代码来展示它。如何解决?

代码:

    void TestMethod(string fileUrl)
    {
        HttpWebRequest req = WebRequest.Create(fileUrl) as HttpWebRequest;
        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
        long contentSize = resp.ContentLength;

        MessageBox.Show(contentSize.ToString());
    }
    private void TestButton_Click(object sender, EventArgs e)
    {
        string url1 = "http://www.calprog.com/Sounds/NealMorseDowney_audiosample.mp3";
        string url2 = "http://www.stephaniequinn.com/Music/Canon.mp3";

        TestMethod(url1); //This file size must be 8 MB, but it shows up as 210 kb. This is the problem

        TestMethod(url2); //This file size is correct here, about 2.1 MB 
    }

我认为您不能通过这种方式(使用 HttpWebRequest)访问此 url。

如果您尝试获取响应文本:

    HttpWebRequest req = WebRequest.Create(fileUrl) as HttpWebRequest;
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
    using (var streamreader = new StreamReader(resp.GetResponseStream()))
    {
        var r = streamreader.ReadToEnd();
        long contentSize = r.Length;
        Console.WriteLine(contentSize.ToString());
    }

您将收到以下回复:

<html><head><title>Request Rejected</title></head><body>The requested URL was rejected. If you think this is an error, please contact the webmaster. <br><br>Your support ID is: 2719994757208255263</body></html>

您必须设置 UserAgent 才能获得完整的响应。像这样:

req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0";

通过设置这个值,服务器会认为您的程序是 Firefox 浏览器。

所以这几行代码应该可以解决问题:

   void TestMethod(string fileUrl)
   {
       HttpWebRequest req = WebRequest.Create(fileUrl) as HttpWebRequest;
       req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0";
       HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
       long contentSize = resp.ContentLength;
       Console.WriteLine(contentSize.ToString());
    }

祝你有美好的一天!