在我的问题Can't login with HttpWebRequests之后,我成功登录。我得到的页面上显示“感谢您登录”,但之后我似乎没有记录英寸
对我而言,这看起来像是一个cookie问题。在firebug中,cookie似乎是HttpOnly可能是一个问题?如何使HttpWebRequest
使用Cookie?
这是我用来登录的代码:
string url = "http://www.warriorforum.com/login.php?do=login";
var bytes = Encoding.Default.GetBytes(@"vb_login_username=USERNAME&cookieuser=1&vb_login_password=&s=&securitytoken=guest&do=login&vb_login_md5password=d9350bad28eee253951d7c5211e50179&vb_login_md5password_utf=d9350bad28eee253951d7c5211e50179");
var container = new CookieContainer();
var request = (HttpWebRequest)(WebRequest.Create(url));
request.CookieContainer = container;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.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; InfoPath.3)";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.CookieContainer = container;
using (var requestStream = request.GetRequestStream())
requestStream.Write(bytes, 0, bytes.Length);
var requestResponse = request.GetResponse();
using (var responsStream = requestResponse.GetResponseStream())
if (responsStream != null)
{
using (var responseReader = new StreamReader(responsStream))
{
var responseStreamReader = responseReader.ReadToEnd();
richTextBox1.Text = responseStreamReader; //this is to read the page source after the request
}
}
}
答案 0 :(得分:2)
HttpWebRequest.CookieContainer
的手册页说:
CookieContainer属性提供CookieContainer类的实例,该类包含与此请求关联的Cookie。
你这样做:
var container = new CookieContainer();
因此,在每个请求中,您都会从没有任何Cookie的新CookieContainer
开始。使container
成为类成员并仅实例化一次。