用WebRequest登录网站

来源:互联网 发布:unity3d塔防案例教程 编辑:程序博客网 时间:2024/04/29 18:05

CookieContainer cookie = new CookieContainer();

string postData = "gsid=17&username=***&password=***";
string strUrl = "
http://www.eln.com.cn/login.php";
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strUrl);
myRequest.Method = "POST";
myRequest.Referer = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5 (.NET CLR 3.5.21022)";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
myRequest.CookieContainer = cookie;
 
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();

 

HttpWebResponse wmvRes = (HttpWebResponse)myRequest.GetResponse();
cookie.Add(wmvRes.Cookies);

 

myRequest = (HttpWebRequest)WebRequest.Create("http://www.eln.com.cn/learn/video.php?vbox=&countid=&s=548f3217bd6f191cd4bc518b806460aa&bianhao=N0102&jie=0101&grkcid=2706377");
myRequest.Method = "GET";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.CookieContainer = cookie;
myRequest.KeepAlive = false;
myRequest.AllowAutoRedirect = true; 

 wmvRes = (HttpWebResponse)myRequest.GetResponse();

StreamReader wmvRead = new StreamReader(wmvRes.GetResponseStream(), System.Text.Encoding.Default);
StreamWriter wmvWrite = new StreamWriter(Application.StartupPath + @"/xxx.htm");
wmvWrite.Write(wmvRead.ReadToEnd());
wmvWrite.Flush();
wmvWrite.Close();
wmvRead.Close();