用System.Web.HttpRequest模拟一个form的post
比如果我的form是这样的
<form method=post action="http://www.domain.com/abc.aspx">
<input type=text name="username">
<input type=password name="pwd">
</form>
我想用code来模拟这个post
http://www.west-wind.com/presentations/dotnetWebRequest/dotnetWebRequest.htm
可以看这个页面
using System.IO;
using System.Net;
String url = "http://www.domain.com/abc.aspx";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//if your username and pwd contains special chars, you need to call HttpUtility.UrlEncode to encode the values
string s = "username=abc&pwd=def";
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes (s);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes,0,requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
String line = streamReader.ReadToEnd();
streamReader.Close();
res.Close();
<form method=post action="http://www.domain.com/abc.aspx">
<input type=text name="username">
<input type=password name="pwd">
</form>
我想用code来模拟这个post
http://www.west-wind.com/presentations/dotnetWebRequest/dotnetWebRequest.htm
可以看这个页面
using System.IO;
using System.Net;
String url = "http://www.domain.com/abc.aspx";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//if your username and pwd contains special chars, you need to call HttpUtility.UrlEncode to encode the values
string s = "username=abc&pwd=def";
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes (s);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes,0,requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
String line = streamReader.ReadToEnd();
streamReader.Close();
res.Close();