Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending HTTP POST with System.Net.WebClient

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 
like image 571
Endy Tjahjono Avatar asked Nov 22 '11 04:11

Endy Tjahjono


People also ask

How do I make a HTTP POST Web request?

Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method: wRequest. Method = "POST"; Get the stream that holds request data by calling the GetRequestStream method.

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.

What is system net WebClient?

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI. The WebClient class uses the WebRequest class to provide access to resources.


2 Answers

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.

like image 65
Endy Tjahjono Avatar answered Sep 19 '22 08:09

Endy Tjahjono


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 
like image 21
carlosfigueira Avatar answered Sep 22 '22 08:09

carlosfigueira