为什么 WebClient.DownloadFile 方法不起作用并说 "JSON not found" 而 URL 使用 Web 浏览器工作?

Why does the WebClient.DownloadFile method not work and say "JSON not found" while the URL is working using a Web browser?

我正在尝试使用以下代码使用 C# 下载文件:

using (var client = new WebClient())
{
    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    string downloadUrl = "https://data.3dbag.nl/cityjson/v21031_7425c21b/3dbag_v21031_7425c21b_8044.json";
    string destinationFile = "test.json";
    client.DownloadFile(downloadUrl, destinationFile);
}

一个例子url是这样的:https://data.3dbag.nl/cityjson/v21031_7425c21b/3dbag_v21031_7425c21b_8044.json

此 URL 在我的浏览器中工作,但在 C# 中我收到 (404) Not Found 错误。有谁知道如何解决这个问题?

看起来这个服务器需要 header Accept-Encoding: gzip:

using (var client = new WebClient())
{
    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    string downloadUrl = "https://data.3dbag.nl/cityjson/v21031_7425c21b/3dbag_v21031_7425c21b_8044.json";
    string destinationFile = "test.json";
    client.Headers.Add("Accept-Encoding", "gzip"); //<-- add Header!
    client.DownloadFile(downloadUrl, destinationFile);
}

您将获得“压缩响应”。

所以你必须解压缩响应!

Compression/Decompression string with C#