【问题标题】:Why do I get an exception when using WebClient.DownloadData for a url?为什么将 WebClient.DownloadData 用于 url 时会出现异常?
【发布时间】: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


【解决方案1】:

这个特定的服务器需要一个用户代理字符串来指示浏览器正在使用中。这有效:

    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");
        }
    }

我使用下载文件没有什么特别的原因——只是在玩弄一些东西。如果您在应用程序中需要字节数组,那么一定要使用 downloaddata :)

【讨论】:

  • 太好了。感谢您的帮助。
最近更新 更多