我有 2 个网址:
https://static.summitracing.com/global/images/prod/xlarge/cse-5160_xl.jpghttp://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
此特定服务器需要一个指示浏览器正在使用的用户代理字符串。这有效:
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");
}
}
我没有特别的原因使用下载文件 - 只是玩东西。如果您的应用程序中需要字节数组,那么一定要使用下载数据:)