Making a cURL call in C#

smohamed picture smohamed · Oct 28, 2011 · Viewed 215k times · Source

I want to make the following curl call in my C# console application:

curl -d "text=This is a block of text" \
    http://api.repustate.com/v2/demokey/score.json

I tried to do like the question posted here, but I cannot fill the properties properly.

I also tried to convert it to a regular HTTP request:

http://api.repustate.com/v2/demokey/score.json?text="This%20is%20a%20block%20of%20text"

Can I convert a cURL call to an HTTP request? If so, how? If not, how can I make the above cURL call from my C# console application properly?

Answer

casperOne picture casperOne · Oct 28, 2011

Well, you wouldn't call cURL directly, rather, you'd use one of the following options:

I'd highly recommend using the HttpClient class, as it's engineered to be much better (from a usability standpoint) than the former two.

In your case, you would do this:

using System.Net.Http;

var client = new HttpClient();

// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new [] {
    new KeyValuePair<string, string>("text", "This is a block of text"),
});

// Get the response.
HttpResponseMessage response = await client.PostAsync(
    "http://api.repustate.com/v2/demokey/score.json",
    requestContent);

// Get the response content.
HttpContent responseContent = response.Content;

// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
    // Write the output.
    Console.WriteLine(await reader.ReadToEndAsync());
}

Also note that the HttpClient class has much better support for handling different response types, and better support for asynchronous operations (and the cancellation of them) over the previously mentioned options.