C#模拟post提交的实现方法

此方法可以在c#后台实现表单以post方式提交的方法;

其中参数:postData 为提交参数

形如:pastData=“username=aaa&userpwd=bbb”;

posturl 为提交事件指定的路径

public string GetPage(string posturl,string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
byte[] da<wbr>ta = encoding.GetBytes(postData);<br> // 准备请求...<br> try<br> {<br> // 设置参数<br> request = WebRequest.Create(pasturl) as HttpWebRequest;<br> CookieContainer cookieContainer = new CookieContainer();<br> request.CookieContainer = cookieContainer;<br> request.AllowAutoRedirect = true;<br> request.Method = "POST";<br> request.ContentType = "application/x-www-form-urlencoded";<br> request.ContentLength = da<wbr>ta.Length;<br> outstream = request.GetRequestStream();<br> outstream.Write(da<wbr>ta, 0, da<wbr>ta.Length);<br> outstream.Close();<br> //发送请求并获取相应回应数据<br> response = request.GetResponse() as HttpWebResponse;<br> //直到request.GetResponse()程序才开始向目标网页发送Post请求<br> instream = response.GetResponseStream();<br> sr = new StreamReader(instream, encoding);<br> //返回结果网页(html)代码<br> string content = sr.ReadToEnd();<br> string err = string.Empty;<br> return content;<br> }<br> catch (Exception ex)<br> {<br> string err = ex.Message;<br> return string.Empty;<br> }<br> }</wbr></wbr></wbr></wbr>

你可能感兴趣的:(post)