0

我正在设置一些这样的 HTTP 请求标头:

        this.Url = new Uri(u);
        HttpWebRequest http = (HttpWebRequest)WebRequest.Create(Url);
        WebResponse response = http.GetResponse();

        //headers
        http.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0\r\n";
        http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
        http.Headers.Add("Accept-Encoding", "gzip,deflate,sdch'r'n");
        http.Headers.Add("Accept-Language", "en-US,en;q=0.9\r\n");
        http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n");

我像这样捕捉它们:

            for (count = 0; count < http.Headers.Keys.Count; count++)
        {
            headerKey = http.Headers.Keys[count];
            headerValue = http.Headers[headerKey];

            if (headerValue != null)
            {
                if (headerKey == null)
                {
                    requestbuffer.Append(headerValue);
                    requestbuffer.Append(Newline); 
                }
                else
                {
                    requestbuffer.Append(headerKey + ": " + headerValue);
                    requestbuffer.Append(Newline);
                }
            }
        }

当我运行测试工具时,一切似乎都很好:

  • 主机:domain.com
  • 连接:保持活动
  • 用户代理:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0)Gecko/20100101 Firefox/17.0
  • 接受:text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8
  • 接受编码:gzip,deflate,sdch 接受语言:en-US,en;q=0.9
  • 接受字符集:ISO-8859-1,utf-8;q=0.7,*;q=0.3

但是在 Wireshark 和 Fiddler 中,仅发送以下标头:

  • 获取/HTTP/1.1
  • 主机:domain.com

知道为什么会这样吗?

4

2 回答 2

3

调用http.GetResponse(). 那是发送请求之后。将其更改为:

this.Url = new Uri(u);
HttpWebRequest http = (HttpWebRequest)WebRequest.Create(Url);

//headers
http.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0\r\n";
http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
http.Headers.Add("Accept-Encoding", "gzip,deflate,sdch'r'n");
http.Headers.Add("Accept-Language", "en-US,en;q=0.9\r\n");
http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n");

using (WebResponse response = http.GetResponse())
{
    // Do whatever
}

(请注意,您确实应该处理响应。)

于 2012-12-07T14:22:03.257 回答
1

是的,您在发送请求后设置标头。

试试这个:

    //headers
    http.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0\r\n";
    http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
    http.Headers.Add("Accept-Encoding", "gzip,deflate,sdch'r'n");
    http.Headers.Add("Accept-Language", "en-US,en;q=0.9\r\n");
    http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n");

    //Added diesposal of response too
    using (WebResponse response = http.GetResponse())
    {
    }
于 2012-12-07T14:22:58.217 回答