How to send Parameters Data using WebClient POST request in C#?


(summerbreeze384) #1


I was wondering if there is any recommended (best & easy & clean) method to send Data Parameters using WebClient POST HTTP request using C#.

Thanks in advance!

(Yassine) #3

I needed to do similar thing before and I did it this way;

string url = ""; // Just a sample url
WebClient wc = new WebClient();
wc.QueryString.Add("parameter1", "Hello world");
wc.QueryString.Add("parameter2", "");
wc.QueryString.Add("parameter3", "parameter 3 value.");
var data = wc.UploadValues(url, "POST", wc.QueryString);
// data here is optional, in case we recieve any string data back from the POST request.
var responseString = UnicodeEncoding.UTF8.GetString(data);

I used WebClient class to create my POST request, and I’ve used WebClient.QueryString to pass parameters to the POST request. It’s really recommended that you use that method above, It handles weird characters and URL parsing correctly on your behalf so you won’t need to worry about encrypting/decrypting your parameters.

Afterward, I’m using the WebClient.UploadValues function, to send out the POST request.

Don’t forget to use “POST” as your method.

And finally (optionally) you may receive a reply back from the server through the WebClient.UploadValues method itself.

(Jonathan Jr) #4

You can also UploadValues, with a Dictionary or a List. Something like NameValueCollection Class.
Which allows you to associate any given string key with a string value, without the extra overhead of having a Dictionary<string, string> but to a big extent they work just the same.

Here is an example using NameValueCollection to gather data to be sent out using WebClient.UploadValues method, same as @yassine did above. but from a different angle:

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", "");
parameters.Add("parameter3", "parameter 3 value.");

/* Always returns a byte[] array data as a response. */
var response_data = client.UploadValues(url, method, parameters);

// Parse the returned data (if any) if needed.
var responseString = UnicodeEncoding.UTF8.GetString(data);

That’s all you need to do.