c# - 使用 WebClient C# 添加请求 header

标签 c# webclient request-headers

我有以下代码,用于将网页下载到字节数组中,然后使用 Response.Write 打印它:

WebClient client = new WebClient();

byte[] data = client.DownloadData(requestUri);

  /***********        Init response headers    ********/
  WebHeaderCollection responseHeaders = client.ResponseHeaders;
  for (int i = 0; i < responseHeaders.Count; i++)
       {
            Response.Headers.Add(responseHeaders.GetKey(i), responseHeaders[i]);
       }
  /***************************************************/

除了响应 header ,我还需要添加请求 header 。我尝试使用以下代码来完成:

  /***********        Init request headers    ********/
  NameValueCollection requestHeaders = Request.Headers;
  foreach (string key in requestHeaders)
  {
      client.Headers.Add(key, requestHeaders[key]);
  }
  /***************************************************/

但是它不起作用,我得到以下异常:

必须使用适当的属性修改此 header 。参数名称:名称

有人可以帮我解决这个问题吗?使用 WebClient 添加请求 header 的正确方法是什么?

谢谢。

最佳答案

header 集合“保护”了一些可能的 header ,如此处的 msdn 页面所述:http://msdn.microsoft.com/en-us/library/system.net.webclient.headers.aspx

该页面似乎提供了您需要的所有答案,但引用了重要部分:

Some common headers are considered restricted and are protected by the system and cannot be set or changed in a WebHeaderCollection object. Any attempt to set one of these restricted headers in the WebHeaderCollection object associated with a WebClient object will throw an exception later when attempting to send the WebClient request.

Restricted headers protected by the system include, but are not limited to the following:

Date

Host

In addition, some other headers are also restricted when using a WebClient object. These restricted headers include, but are not limited to the following:

Accept

Connection

Content-Length

Expect (when the value is set to "100-continue"

If-Modified-Since

Range

Transfer-Encoding

The HttpWebRequest class has properties for setting some of the above headers. If it is important for an application to set these headers, then the HttpWebRequest class should be used instead of the WebRequest class.

我怀疑这是因为许多 header (例如 Date 和 host)必须根据不同的请求进行不同的设置。你不应该复制它们。实际上,我个人可能会建议您不要复制其中任何一个。放入您自己的用户代理 - 如果您获得的页面依赖于某个值,那么我认为您希望确保始终发送有效值,而不是依赖原始用户为您提供该信息。

基本上是弄清楚你需要做什么,而不是在没有完全理解你在做什么的情况下找到有用的东西并去做。

关于c# - 使用 WebClient C# 添加请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7596417/

相关文章:

c# - WCF 真的会取代.NET Remoting 吗?

c# - 使用 Webclient 的 SharePoint 身份验证

javascript - $.ajaxSetup 不工作

javascript - 如何在 Cordova 上设置请求 header 的特定来源?

c# - 是否有可能使枚举自动生成其值

c# - 重用上下文菜单

powershell - 如何在 powershell 中为简单的 https 下载设置默认的 Default SSLContext?

.net - 在 PowerShell 中使用 System.Net.WebClient 通过 SAN 证书访问 HTTPS URL

spring-boot - 我如何记录http请求的主机头(Spring Boot)

c# - 在开发 facebook 图网站时如何使用本地主机?