Making a cURL call to from C#

I had the need to make cURL calls from C# to a call several classifiers I built for an AI proof of concept project.  I struggled a bit getting the headers and syntax correct so I thought I’d share the result in hopes that it may help someone else with a similar need.  I found a few cURL wrappers for C# but found those to be heavy, complicated and unnecessary after much experimentation.

Although this example is specific to Metamind, I think the same general idea would work for any cURL call.

Here is the method that calls the service:

public async Task<string[]> CallCurlService(string strClassifierID, string strImagePath)
    string[] strRetval;
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", mstrCredentials);
    StringContent stringContent = new StringContent("{\"classifier_id\":" + strClassifierID + ",\"image_url\":\"" + strImagePath + "\"}");
    HttpResponseMessage response = await client.PostAsync(mstrMetamindUrl, stringContent);
    HttpContent responseContent = response.Content;// Get the response content.
    using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))// Get the stream of the content.
        JObject jsonResult = JObject.Parse(await reader.ReadToEndAsync());
        string strResult = jsonResult.ToString();
        string strCategory = jsonResult["predictions"].First["class_name"].ToString();
        string strProbability = Math.Round(((double)jsonResult["predictions"].First["prob"] * 100), 2).ToString() + "%";
        strRetval = new string[] { strCategory, strProbability };
    return strRetval;

Leave a Reply

Your email address will not be published. Required fields are marked *