HttpWebRequest不发送Headers

时间:2013-07-17 11:05:01

标签: c# .net cookies httpwebrequest user-agent

我正在尝试使用HttpWebRequest类模拟POST Web请求:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(<my url>));
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        request.UserAgent = @"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";

我需要为请求设置Cookie。我尝试过这些方法:

request.Headers.Add(HttpRequestHeader.Cookie, GetGlobalCookies(<cookies url>));

 [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
    const int INTERNET_COOKIE_HTTPONLY = 0x00002000;

    public static string GetGlobalCookies(string uri)
    {
        uint datasize = 1024;
        StringBuilder cookieData = new StringBuilder((int)datasize);
        if (InternetGetCookieEx(uri, null, cookieData, ref datasize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)
            && cookieData.Length > 0) {
            return cookieData.ToString(); //.Replace(';', ',');
        }
        else
        {
            return null;
        }
    }

request.CookieContainer = new CookieContainer();
request.CookieContainer.SetCookies(new Uri(<my url>), GetGlobalCookies(<cookies-url>).Replace(';', ','));

GetGlobalCookies()返回包含我需要的cookie的正确字符串。但在运行requset.GetResponse()后,我在fiddler中的请求看起来像这样:

POST <my url> HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: <my host>
Content-Length: 3
Expect: 100-continue
Connection: Keep-Alive

i=1

如果我将Method更改为GET,则会正确发送cookie,但仍然没有User-Agent:

GET <my url> HTTP/1.1
Cookie: ASP.NET_SessionId=uajwt1ybpde4hudwwizuq2ld
Host: <my host>
Connection: Keep-Alive

为什么HttpWebRequest不发送Cookie和User-Agent标头?

1 个答案:

答案 0 :(得分:8)

好吧,自己弄清楚了。当您调用GetRequestStream()时,HttpWebRequest构造请求体,因此您必须在调用GetRequestStream()之前设置所有必需的头,否则它们将不会被发送。