2008/09/12

How to use HttpWebRequest object submit form data?

請參考:
p2p.wrox.com Forums - WebRequest/WebResponse form submit problem. HELP!

內容介紹如何使用HttpWebRequest送出form的資料,節錄解答的code如下:

string url="http://www.365articles.com/modules.php?name=Your_Account";
string data="username=gogo&user_password=newnewne&op=login";
byte[] buffer=Encoding.UTF8.GetBytes(data);
string result="";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType ="application/x-www-form-urlencoded";
req.ContentLength = buffer.Length;
//req.Proxy = new WebProxy(proxy, true); // ignore for local addresses
req.CookieContainer = new CookieContainer(); // enable cookies

Stream reqst = req.GetRequestStream(); // add form data to request stream

reqst.Write(buffer, 0, buffer.Length);
reqst.Flush();
reqst.Close();

Console.WriteLine("\nPosting data to " + url);
HttpWebResponse res = (HttpWebResponse)req.GetResponse(); // send request,get response
Console.WriteLine("\nResponse stream is: \n");
Stream resst = res.GetResponseStream(); // display HTTP response
StreamReader sr = new StreamReader(resst);
result=sr.ReadToEnd();
using(System.IO.StreamWriter writer=new StreamWriter("C:\\Temp\\checkcheck.html"))
{
writer.Write(result);
}



source by Mystic

90% 症候群