Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send POST with WebClient.DownloadString in C#

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.

like image 922
PorkWaffles Avatar asked Nov 28 '11 00:11

PorkWaffles


People also ask

How do you send parameters data using WebClient POST request in C?

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.

How to POST data to specific url using WebClient in c#?

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.

What does WebClient Downloadstring do?

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.


2 Answers

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.

like image 72
BrokenGlass Avatar answered Oct 09 '22 02:10

BrokenGlass


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));
}
like image 21
Turbot Avatar answered Oct 09 '22 01:10

Turbot