Tuesday, September 15, 2009

using HttpWebRequest and HttpWebResponse classes

Sending form values with GET method is really easy just appened the URL with ? (question mark) followed with name,value pair but how to send values to the form with POST method? hmm this is what i was searching for few days ago and then i found HttpWebRequest and HttpWebResponse classes. It's my introduction with these classes. (Now after more than 2 years, I have realised the importance of these two classes)

Microsoft made it really easy - just use httpWebRequest to make request and httpWebResponse to get response Voila! thats it!
Have a look at the code below:

string GetResponseString(string Url, string postString)
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Url);
httpRequest.Method = "POST";
httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)";
httpRequest.CookieContainer = new CookieContainer();
httpRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytedata = Encoding.UTF8.GetBytes(postString);
httpRequest.ContentLength = bytedata.Length;
httpRequest.CookieContainer = ccContainer;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
ccContainer.Add(httpWebResponse.Cookies);
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
return sb.ToString();
}



Url is the location of page where form exists and poststring is basically of form name:value pair.
For example our page is located @
http://mytechblog.com/formResultpage.aspx, hosting a form with two input fields, named Field1 and Field2. In this case the the postString will be:

string postString = String.Format("field1={0}&field2={1}", "Field 1 Value", "Field 2 Value");

GetResponseString() will return the response stream containing the page generated after form processing..


string szResult = GetResponseString("http://mytechblog.com/formResultpage.aspx",postString);

No comments:

Post a Comment