【发布时间】:2026-01-28 02:10:01
【问题描述】:
我有 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
【问题讨论】:
-
请将异常详细信息粘贴到您的问题中,
WebException可以是任何东西 -
异常中的实际错误消息是什么?
-
抱歉,我已将异常消息添加到问题中。
-
400 只是表示服务器软件认为您的请求无效。这取决于服务器软件来确定,因此每个站点都是不同的。也许您的请求缺少标头或用户代理字符串错误,也许是别的东西,谁知道呢?
-
您可能希望使用
DownloadFile而不是DownloadData。
标签: c# webclient webclient-download