Send POST with WebClient.DownloadString in C#

PorkWaffles picture PorkWaffles · Nov 28, 2011 · Viewed 23.5k times · Source

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.

Answer

BrokenGlass picture BrokenGlass · Nov 28, 2011

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.