Post data using HttpWebRequest in C#

While working around twitter or any other REST API services, you may require to do a post request to web server. If you are using .net can do this either using WebClient class or using HttpWebRequest class. Both these classes exists in System.Net namespace. I am using HttpWebRequest here because HttpWebRequest gives you more fine grained control over your request. WebClient does not. Also webclient encapsulates most of the stuff for you. HttpWebRequest allows to send headers or other customizations.

You can also invoke Web Services using HttpWebRequest class.

//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/DemoApp/Default.aspx") as HttpWebRequest;
//Specifing the Method 
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
    MessageBox.Show(sr.ReadToEnd());
}

It will show some HTML content in the Message box.

You can also access or post data to .net web services. For sending data to webservices, you need to change the URL like following

http://www.dotnetthoughts.net/sample.asmx/HelloWorld.

where HelloWorld is the Web Method name to invoke. It will return an XML after successful operation.

One thought on “Post data using HttpWebRequest in C#

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>