HttpWebResponse对于ContentLength是错误的

时间:2016-09-18 17:25:07

标签: c# http downloading content-length

我有一个HTTP协议的下载方法。但它似乎无法正常工作,有些事情是错误的。我用一些网址来测试它,除了最后一个,它是正确的。网址的ContentLength属性错误。它在运行时显示为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 
    }

1 个答案:

答案 0 :(得分:1)

我认为您不允许以这种方式访问​​此网址(使用HttpWebRequest)。

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

    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());
    }

祝你有个美好的一天!