我有2个网址:
https://static.summitracing.com/global/images/prod/xlarge/cse-5160_xl.jpg http://www.americanbassusa.com/Subwoofers/DX-Series-Images/DX/DX-front.jpg
在Chrome中打开时,它们都可以正确下载相应的图像,但是当使用以下控制台应用程序通过WebClient.DownloadData(String)下载它们时,第二个URL会引发System.Net.WebException。
任何人都可以使我了解为什么会发生这种情况吗?
class Program
{
static void Main(string[] args)
{
const string WorkingUrl = "https://static.summitracing.com/global/images/prod/xlarge/cse-5160_xl.jpg";
const string NonWorkingUrl = "http://www.americanbassusa.com/Subwoofers/DX-Series-Images/DX/DX-front.jpg";
try
{
using (var client = new WebClient())
{
byte[] fileData = client.DownloadData(NonWorkingUrl);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
异常详细信息为:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadData(Uri address)
at System.Net.WebClient.DownloadData(String address)
at ConsoleApp4.Program.Main(String[] args) in C:\\Users\\davidandrewpowell\\source\\repos\\ConsoleApp4\\ConsoleApp4\\Program.cs:line 17
答案 0 :(得分:2)
此特定服务器需要一个表示正在使用浏览器的useragent字符串。这有效:
using (var client = new System.Net.WebClient())
{
client.Headers.Add(System.Net.HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134");
client.DownloadFile(NonWorkingUrl, "c:\\temp\\a");
}
}
没有特别的原因,我使用downloadfile-只是在玩玩。如果您需要在应用中使用字节数组,请务必使用downloaddata:)