35

Is it possible to send HTTP POST with some form data with System.Net.WebClient?

If not, is there another library like WebClient that can do HTTP POST? I know I can use System.Net.HttpWebRequest, but I'm looking for something that is not as verbose.

Hopefully it will look like this:

Using client As New TheHTTPLib
    client.FormData("parm1") = "somevalue"
    result = client.DownloadString(someurl, Method.POST)
End Using
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
Endy Tjahjono
  • 24,120
  • 23
  • 83
  • 123

3 Answers3

67

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

Endy Tjahjono
  • 24,120
  • 23
  • 83
  • 123
  • What does `someUrl` refer to?? I'm trying to log in to a website that has a HTML login-form, it doesn't login. The resulted data is as if I'm anonymous. – Shimmy Weitzhandler Jun 12 '13 at 03:41
  • @Shimmy I haven't tried using webclient on a site that requires login. `someUrl` is URL string, for example `client.UploadValues("http://localhost", "POST", reqparm)`. – Endy Tjahjono Jun 12 '13 at 05:18
  • can we use this POST request (including the parameters call) with the asynchronous call? – gumuruh Apr 07 '14 at 09:14
  • It's working fine, thanks for the answer! But when I call `Net.WebClient.UploadValues` method it's start 7 threads and don't stop these. What could I do about this? – kukko Oct 20 '16 at 14:06
14

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
2

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

faester
  • 14,886
  • 5
  • 45
  • 56