我正在尝试使用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标头?
答案 0 :(得分:8)