我正在尝试登录网站。它应该由POST请求完成。但我需要以某种方式存储cookie。
我的实际代码:
public void botLogin(string userName, string passWord)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string post_data = "username=" + userName + "&password=" + passWord;
byte[] data = encoding.GetBytes(post_data);
var requestUri = "http://registration.zwinky.com/registration/loginAjax.jhtml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var sharedCookies = new CookieContainer();
request.CookieContainer = sharedCookies;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
MessageBox.Show(sr.ReadToEnd());
sr.Close();
stream.Close();
}
我现在如何存储cookie以将其用于其他请求?
答案 0 :(得分:1)
首先,将创建的WebRequest强制转换为HttpWebRequest。这将使您可以访问更多特定于HTTP的属性和方法。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
在应用程序级别定义一个CookieContainer对象,并为每个创建的请求设置该对象。
request.CookieContainer = sharedCookies;
我很确定,HttpWebRequest对象将在下载后存储cookie,以便下一个请求可以使用它们。如果仍然无效,请检查HttpWebResponse对象是否有cookie(同样,不要忘记将响应对象强制转换为该对象)。