Using WebRequest How to POST things, Should I use GetRequestStream? and how to format POST string
Thanks
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 .
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.
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¶m2=value2");
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With