Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST using WebRequest?

Tags:

c#

Using WebRequest How to POST things, Should I use GetRequestStream? and how to format POST string

Thanks

like image 357
Costa Avatar asked Apr 11 '10 14:04

Costa


People also ask

What is the difference between HttpWebRequest and WebRequest?

In a nutshell, WebRequest—in its HTTP-specific implementation, HttpWebRequest—represents the original way to consume HTTP requests in . NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest. And HttpClient is the new and improved way of doing HTTP requests and posts, having arrived with .

What is WebRequest C#?

The WebRequest is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest and FileWebRequest. You use Create method of WebRequest to create an instance of WebRequest. GetResponseStream returns data stream.


2 Answers

var request = WebRequest.Create("http://www.example.com");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    // write to the body of the POST request
    writer.Write("param1=value1&param2=value2");
}
like image 56
Darin Dimitrov Avatar answered Sep 19 '22 02:09

Darin Dimitrov


As an alternative to HttpWebRequest, have a look at WebClient.UploadValues:

var values = new NameValueCollection();
values.Add("param1", "value1");
values.Add("param2", "value2");

new WebClient().UploadValues("http://www.example.com", values);
like image 37
dtb Avatar answered Sep 18 '22 02:09

dtb