1
我的程序應該登錄到一個站點。要登錄,您應該向主頁面發出請求並獲取cookie,然後您應該登錄(http://site.com/auth/login)。當我向主頁面發出請求並獲取cookie時,一切正常,cookie容器中有兩個cookie,但是當我登錄時,只有一個cookie。代碼如下:HttpWebRequest發送1個Cookie而不是2個
public CookieContainer GetCookies()
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://site.com/");
httpWebRequest.CookieContainer = new CookieContainer();
httpWebRequest.Accept = "*/*";
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "ru");
httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; WebMoney Advisor; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Tablet PC 2.0; .NET4.0C; .NET CLR 1.1.4322; .NET4.0E; MALC)";
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
httpWebRequest.Timeout = 30000;
CookieContainer cookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
foreach (Cookie c in response.Cookies)
{
cookieContainer.Add(c);
}
return cookieContainer;
}
public bool Login(string Email, string Password, CookieContainer Cookies)
{
string s = "handle=" + Email + "&password=" + Password;
byte[] bytes = Encoding.ASCII.GetBytes(s);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://site.com/auth/login");
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
httpWebRequest.Referer = "http://www.lockerz.com/";
httpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "ru-RU");
httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; WebMoney Advisor; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Tablet PC 2.0; .NET4.0C; .NET CLR 1.1.4322; .NET4.0E; MALC)";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.CookieContainer = Cookies;
httpWebRequest.ContentLength = (long)bytes.Length;
httpWebRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
httpWebRequest.Timeout = 30000;
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream());
string document = reader.ReadToEnd().Trim();
if (document.IndexOf("Sign Out") > 1)
{
httpWebResponse.Close();
return true;
}
else
{
httpWebResponse.Close();
return false;
}
}
怎麼了? 在此先感謝。
不清楚你如何使用'GetCookies',但有可能第二個響應只返回一個cookie - 你在請求之間使用相同的'CookieContainer',還是你重新創建它? – 2011-05-01 12:59:53
我像'CookieContainer cookies = GetCookies()一樣使用它;如果(!登錄(電子郵件,密碼,cookies)){<...>} – Cracker 2011-05-01 13:15:01