我想從網絡瀏覽器控制切換到http請求自動執行任務的速度。 使用此功能,我可以發佈數據並接收登錄頁面,但不會返回cookie並將其添加到cookie列表中,因此登錄的會話不會傳遞到下一個請求。C#HttpWebRequest網站登錄
//an example call
test("http://websitename.com/loginpage.php", "username=foo&password=123456");
private string test(string url, string data)
{
string responseFromServer;
byte[] byteArray;
Stream dataStream;
HttpWebRequest request;
HttpWebResponse response;
StreamReader reader;
responseFromServer = string.Empty;
try
{
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
byteArray = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteArray.Length;
request.CookieContainer = new CookieContainer();
foreach(Cookie a in cookies)
request.CookieContainer.Add(a);
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse() as HttpWebResponse;
foreach(Cookie a in response.Cookies)
cookies.Add(a);
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception x)
{
x.ToString();
}
return responseFromServer;
}
如何保持登錄狀態?
您可以包括整個HTTP響應(包括標題)? (例如,通過使用[fiddler](http://www.fiddler2.com/)。) –