I know there are a lot of questions about sending HTTP POST requests with C#, but I'm looking for a method that uses WebClient
rather than HttpWebRequest
. Is this possible? It'd be nice because the WebClient
class is so easy to use.
I know I can set the Headers
property to have certain headers set, but I don't know if it's possible to actually do a POST from WebClient
.
var url = "https://your-url.tld/expecting-a-post.aspx" var client = new WebClient(); var method = "POST"; // If your endpoint expects a GET then do it. var parameters = new NameValueCollection(); parameters. Add("parameter1", "Hello world"); parameters. Add("parameter2", "www.stopbyte.com"); parameters.
The WebClient class uses the WebRequest class to provide access to resources. WebClient instances can access data with any WebRequest descendant registered with the WebRequest. RegisterPrefix method. UploadString Sends a String to the resource and returns a String containing any response.
This method retrieves the specified resource. After it downloads the resource, the method uses the encoding specified in the Encoding property to convert the resource to a String. This method blocks while downloading the resource.
You can use WebClient.UploadData()
which uses HTTP POST, i.e.:
using (WebClient wc = new WebClient())
{
byte[] result = wc.UploadData("http://stackoverflow.com", new byte[] { });
}
The payload data that you specify will be transmitted as the POST body of your request.
Alternatively there is WebClient.UploadValues()
to upload a name-value collection also via HTTP POST.
You could use Upload method with HTTP 1.0 POST
string postData = Console.ReadLine();
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers.Add("Content-Type","application/x-www-form-urlencoded");
// Upload the input string using the HTTP 1.0 POST method.
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
byte[] byteResult= wc.UploadData("http://targetwebiste","POST",byteArray);
// Decode and display the result.
Console.WriteLine("\nResult received was {0}",
Encoding.ASCII.GetString(byteResult));
}
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