谁可以用 c# webrequest 下载这张图片?

Who can download this image with c# webrequest?

图片 link : http://media.isna.ir/content/1435516708689_Mehdi+Ghasemi+%2818+of+18%29.jpg

我的代码是:

WebRequest req = WebRequest.Create("http://media.isna.ir/content/1435516708689_Mehdi+Ghasemi+%2818+of+18%29.jpg");

WebResponse response = req.GetResponse();

Stream stream = response.GetResponseStream();
Image img = Image.FromStream(stream);
stream.Close();

错误信息:

The remote server returned an error: (500) Internal Server Error.

但我可以在 Google Chrome 和 Firefox 中看到该图像。

当然我可以从另一个网站下载另一个图像。为什么这个网站的行为会出错?

你需要像这样添加headers

WebRequest req = WebRequest.Create("http://media.isna.ir/content/1435516708689_Mehdi+Ghasemi+%2818+of+18%29.jpg");
            HttpWebRequest request = (HttpWebRequest)req;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            WebResponse response = request.GetResponse();

            Stream stream = response.GetResponseStream();
            Image img = Image.FromStream(stream);
            stream.Close();

发生这种情况是因为某些服务器拒绝未指定用户代理的请求。更改您的方法以传递用户代理,它将起作用。

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://media.isna.ir/content/1435516708689_Mehdi+Ghasemi+%2818+of+18%29.jpg");

// THIS LINE IS THE IMPORTANT ONE
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
                "Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
                ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
                "InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";

HttpWebResponse response = (HttpWebResponse)req.GetResponse();

Stream stream = response.GetResponseStream();
Image img = Image.FromStream(stream);
stream.Close();