模拟登陆,目的是方便抓取需要登陆后浏览的论坛帖子。
代码摘录如下(注意黑体部分):
//Request #1 (the login)
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST" ;
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded" ;
objRequest.CookieContainer = new CookieContainer();
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
//retain the cookies
foreach (Cookie cook in objResponse.Cookies)
{
myContainer.Add(cook);
}
//Check out the html.
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()) )
{
String test = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}