我需要下载图片(验证码)。 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;
}
}
}
答案 0 :(得分:5)
我认为这是因为服务器检测到请求不是由Web浏览器发出的。如果指定用户代理标头,则会正确下载映像:
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)