Making a Curl Call in C#

Making a cURL call in C#

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

  • HttpWebRequest/HttpWebResponse
  • WebClient
  • HttpClient (available from .NET 4.5 on)

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.

How to make cURL call in C#

If you just want something simple I would use the HttpClient class built into the .Net Framework like this:

using System.Net.Http;
using System.Threading.Tasks;

namespace ScrapCSConsole
{
class Program
{
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Host = "example.com";
Task<string> task = client.GetStringAsync("https://serverName/clearprofile.ashx");
task.Wait();
Console.WriteLine(task.Result);
}
}
}

For more complex stuff, you can also use the HttpWebRequest class like this:

using System;
using System.IO;
using System.Net;

namespace ScrapCSConsole
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.co.uk");

request.Host = "example.com";

HttpStatusCode code;
string responseBody = String.Empty;

try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
code = response.StatusCode;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseBody = reader.ReadToEnd();
}
}
}
catch (WebException webEx)
{
using (HttpWebResponse response = (HttpWebResponse)webEx.Response)
{
code = response.StatusCode;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseBody = reader.ReadToEnd();
}
}
}

Console.WriteLine($"Status: {code}");
Console.WriteLine(responseBody);
}
}
}

Curl Request In C#

The problem was that I wasn't writing the file contents to the stream from the requests .GetRequestStream(). Once I wrote the contents there, it appeared on the other end. New stripped down code is

  // open the web request stream
using (var stream = request.GetRequestStream())
{
byte[] file = File.ReadAllBytes(fileName);

stream.Write(file, 0, file.Length);

stream.Close();
}

cURL call in C#

I found the issue. Apparently the request fails when you pass an @ sign ( like in the email username ) in the username field so it must be Converted to a base 64 string. Here is the code just in case someone else runs into this:

    string url = "https://website.com/events.csv"; 
WebRequest myReq = WebRequest.Create(url);
string username = "username";
string password = "password";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
Console.ReadLine();

Rest api get curl C#

The curl request would be represented like this in C#

using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.united.com/v1/accounts"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer kgffj*dfkgj40fdgjkjkdfjUHHHDNhdfj");

var response = await httpClient.SendAsync(request);
}
}

I could not test this code as the url https://api.united.com/v1/accounts times out from my system. But This should work.

As others have pointed out you should not need to convert the token to base 64 as its not converted to base64 in the curl

I am assuming that you want to perform the same request that you would run if you use the curl command in your question

The code provided above fixes the http request.
The response object in the above code is of Type HttpResponseMessage
This object has a HttpResponseMessage.Content Property on it
This Content is of type HttpContent and it has a public method ReadAsStringAsync() which will

Serialize the HTTP content to a string as an asynchronous operation.

and that is your JSON content that you are looking for.

So your code should look like this

public static async Task<string> GetData()
{
using (var httpClient = new HttpClient())
{

using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.united.com/v1/accounts"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer kgffj*dfkgj40fdgjkjkdfjUHHHDNhdfj");

var response = await httpClient.SendAsync(request);

return await response.Content.ReadAsStringAsync();
}
}
}

This method is an async method,Since the code you provided in the question is not async you would need to use

string json = GetData().Result;

if you want to use it in a non async function
or if you change your method calling this method to async then you can use the await keyword like this

string json = await GetData();


Related Topics



Leave a reply



Submit