This example demonstrates how to send a POST request using the HttpClient library.

For this example you will need the following using directives:

using CodeScales.Http;
using CodeScales.Http.Methods;
using CodeScales.Http.Entity;
using CodeScales.Http.Common;

We start by creating the HttpClient object and the POST method (very much the same as we created the GET method). (lines 1-2)

We then create a List of “NameValuePair” and populate it with the values we want to send. Any other C# type (like int) that you want to pass as a parameter will have to be converted to string since in “HTTP Form Post” all parameters are passed as strings. (lines 4-5)

Once we have the list of parameters, we create a UrlEncodedFormEntity which is the entity that transforms our list of parameters to an “HTTP Form Post” content. We will then assign the UrlEncodedFormEntity to be the PostMethod’s entity. (lines 7-8)

To Conclude, we will execute the PostMethod (line 10). Once executed, as before, we can check the status code, and print the markup of the response.

HttpClient client = new HttpClient();
HttpPost postMethod = new HttpPost(new Uri("http://www.w3schools.com/asp/demo_simpleform.asp"));

List<NameValuePair> nameValuePairList = new List<NameValuePair>();
nameValuePairList.Add(new NameValuePair("fname", "brian"));
            
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Encoding.UTF8);
postMethod.Entity = formEntity;
            
HttpResponse response = client.Execute(postMethod);

Console.WriteLine("Response Code: " + response.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));