5

我正在尝试使用 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() 之后,我在提琴手中的请求如下所示:

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

如果我将方法更改为 GET,则正确发送 cookie,但仍然没有用户代理:

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

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

4

1 回答 1

11

好的,我自己想通了。HttpWebRequest 在调用 GetRequestStream() 时会构造请求体,因此在调用 GetRequestStream() 之前必须设置所有需要的 headers,否则不会发送。

于 2013-07-26T04:18:42.693 回答