【问题标题】:Download zip file without using webclient c#在不使用 webclient c# 的情况下下载 zip 文件
【发布时间】:2019-01-10 12:12:41
【问题描述】:

想要在不使用 Web 客户端的情况下下载 zip 文件,因为出现错误“远程服务器返回错误:(403) Forbidden。”在将正确的标头传递给请求之后。

需要 webclient 和 httpwebrequest 的替代方案。

提前致谢!

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
HttpWebResponse WebResponse = (HttpWebResponse)request.GetResponse();

using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(URL);

                    response.EnsureSuccessStatusCode();

                    string responseBody = await response.Content.ReadAsStringAsync();
                    // Above three lines can be replaced with new helper method below
                    // string responseBody = await client.GetStringAsync(uri);

                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }

【问题讨论】:

  • 无论您使用哪种方法都会收到 403 响应,这表明您要么没有传递正确的凭据,要么没有正确传递它们。如果您可以发布您的代码(当然不包括任何敏感信息)以帮助确定它是哪一个并确定问题是否是两者中的后者,这将有所帮助。
  • 您应该向我们展示“将正确的标头传递给请求”。 WebClient 和 WebRequest 是旧的但没有损坏。错误是你的。
  • 发布的代码。请检查并告诉我
  • 您根本没有设置任何标题。请参阅 WebCLient.Credentials 并了解如何使用它们。
  • Google:“你使用的 httpclient 错误”。

标签: c# web-scraping


【解决方案1】:

您可以使用HttpClient,它已在 ASP.NET Web API 版本中引入,也包含在 .NET Core 中。

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2

您的服务器似乎需要身份验证才能下载 ZIP 文件 - 您可以使用 HttpClient 执行此操作,具体取决于您的服务器需要哪种类型的身份验证。

【讨论】:

  • 仍然得到相同的响应'远程服务器返回错误:(403)禁止。'
  • 如前所述,您的服务器需要身份验证和授权(403 表示您可能已通过身份验证但您没有权限 = 未授权)
  • 谢谢,我会检查
  • 也这样做了。使用适当的令牌设置授权标头。问题未解决
猜你喜欢
  • 1970-01-01
  • 2014-06-20
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2020-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多