最近接了个小项目,用到一个技术需要模拟POST向Web服务器发送请求来进行登录,下面写一下主要代码。
string strId = "admin";//用户名
string strPassword = "xxxxx";//密码
//string strsubmit = "YES";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=" + strId;
postData += ("&password=" + strPassword);
//postData += ("&Accept=" + strsubmit);
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.csharpcn.com/login.aspx");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
// Get response
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
//Response.Write(content);
textBox1.Text = content;
以上代码放到一个方法里就可以获取登录CSHARPCN后的第一个页面了。