1
我有一個HTTP協議的下載方法。但它似乎不能正常工作,有些事情是錯誤的。我用一些url來源測試了它,除了最後一個,它是正確的。該ContentLength
屬性是錯誤的網址。它在運行時顯示爲210 kb,但實際上爲8 MB。我將通過分享我的代碼來展示它。如何解決它?HttpWebResponse對於ContentLength是錯誤的
代碼:
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
}
它工作正常。我不喜歡使用StreamReader,因爲它等待要下載的文件。設置'UserAgent'更好,並且可以返回正確的大小。最後,這Mozilla'UserAgent'是否適用於所有Http源?因爲我需要它是一般化的。謝謝@Quentin。 –
是的,這個用戶代理將與所有的http源一起工作。 (如果URL可以通過標準瀏覽器訪問) –
感謝您的快速回復先生!很好的答案 –