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()))
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))

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

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

Anuraj is currently working as Technical Lead. He is a regular speaker on Technology events. He has more than 11+ years experience with Microsoft.Net Technologies.

Facebook Twitter LinkedIn Google+