【问题标题】:Download image issue in C#. Downloads html instead [closed]在 C# 中下载图像问题。改为下载 html [关闭]
【发布时间】:2012-02-29 17:22:34
【问题描述】:

我需要下载一些图片(验证码)。 This 就是一个例子。

如果您在任何浏览器中打开该链接,它会显示一个图像,但是当我尝试以代码下载该图像时,它会给我一个 html 页面,其中仅包含指向主页的链接 - http://www.networksolutions.com/。我究竟做错了什么?下面是两个代码示例:

byte[] data = new WebClient().DownloadData(imgURL);

AND

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(imgURL);
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.Headers.Add("Accept-Language", "en-us,en;q=0.5");
req.Headers.Add("Accept-Encoding", "gzip,deflate");
req.KeepAlive = true;

byte[] data;

using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
    using (Stream s = response.GetResponseStream())
    {
        int contentLength = (int)response.ContentLength;
        data = new byte[contentLength];

        for (int pos = 0; pos < contentLength; ++pos)
        {
            int len = s.Read(data, pos, contentLength - pos);                                            
            pos += len;
        }
    }
}

【问题讨论】:

  • 什么是imgURL?您提供的链接似乎指向将生成图像的页面。不是图像本身。
  • 不,那个网址是实际的图片网址。

标签: c# image http httpwebrequest webclient


【解决方案1】:

我认为这是因为服务器检测到请求不是由网络浏览器发出的。如果您指定用户代理标头,它会正确下载图像:

var wc = new WebClient();
wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2";
byte[] data = wc.DownloadData(imgURL)

【讨论】:

  • 你是对的!我怎么能忘记设置用户代理?我的错。
猜你喜欢
  • 2021-10-08
  • 2017-06-27
  • 1970-01-01
  • 2013-03-07
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 2012-09-26
相关资源
最近更新 更多