问题描述
我使用以下代码将网页下载到字节数组中,然后使用 Response.Write 打印:
I have the following code with which I download a web-page into a byte array and then print it with 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]);
}
/***************************************************/
除了响应头之外,我还需要添加请求头.我尝试使用以下代码进行操作:
Besides of the response headers, I need to add request headers as well. I try to do it with the following code:
/*********** Init request headers ********/
NameValueCollection requestHeaders = Request.Headers;
foreach (string key in requestHeaders)
{
client.Headers.Add(key, requestHeaders[key]);
}
/***************************************************/
但是它不起作用,我得到以下异常:
However it does not work and I get the following exception:
必须使用适当的属性修改此标头.参数名称:名称
This header must be modified using the appropriate property.Parameter name: name
有人能帮我解决这个问题吗?使用 WebClient 添加请求标头的正确方法是什么?
Could anybody help me with this? What's the correct way of adding request headers with WebClient?
谢谢.
推荐答案
标头集合保护"了一些可能的标头,如此处的 msdn 页面所述:http://msdn.microsoft.com/en-us/library/system.net.webclient.headers.aspx
That page seems to give all the answer you need but to quote the important part:
Restricted headers protected by the system include, but are not limited to the following:
Date
Host
此外,其他一些头文件在使用时也受到限制WebClient 对象.这些受限制的标头包括但不包括限于以下内容:
Accept
Connection
Content-Length
Expect (when the value is set to "100-continue"
If-Modified-Since
Range
Transfer-Encoding
HttpWebRequest 类具有用于设置上述某些内容的属性标题.如果应用程序设置这些标头很重要,那么应该使用 HttpWebRequest 类而不是 WebRequest班级.
基本上找出你需要做的事情,而不是在没有完全理解你在做什么的情况下找到有效的事情然后去做.
这篇关于使用 WebClient C# 添加请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!