gpt4 book ai didi

c# - HttpWebResponse 对于 ContentLength 是错误的

转载 作者:可可西里 更新时间:2023-11-01 17:32:11 26 4
gpt4 key购买 nike

我有一个HTTP协议(protocol)的下载方法。但它似乎无法正常工作,出了点问题。我用一些 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
}

最佳答案

我认为您不允许以这种方式访问​​此 url(使用 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());
}

祝你有美好的一天!

关于c# - HttpWebResponse 对于 ContentLength 是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com