-1

How do you convert a curl to be used in C# using HttpClient?

Here is the curl call that I need to use:

Request:
curl -i \
-X POST \
-H "X-Version: 1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer Your Authorization Token" \
-H "Accept: application/json" \
-d '{"text":"Test Message","to":["Recipients Mobile Number"]}' \
-s \
https://api.clickatell.com/rest/message

I have basic knowledge of HttpClient and I know nothing of curl calls so this is what I could figure from Googling. Below is my code, not sure if it is correct?

using (var httpClient = new HttpClient())
{
     httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "abcdefghij0123456789");

     httpClient.DefaultRequestHeaders.Accept.Clear();
     httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

     httpClient.DefaultRequestHeaders.Add("X-Version", "1");

     StringContent stringContent = new StringContent("{\"text\":\"Test Message\",\"to\":[\"27936906909\"]}");
     stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

     HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("https://api.clickatell.com/rest/message", stringContent);
     if (httpResponseMessage.IsSuccessStatusCode)
     {
     }
     else
     {
          string failureMsg = "HTTP Status: " + httpResponseMessage.StatusCode.ToString() + " - Reason: " + httpResponseMessage.ReasonPhrase;
     }

     //string sjson = await httpResponseMessage.Content.ReadAsAsync<string>();
     //return sjson;
}

Everything looks correct to be but when I run it then I keep on getting a bad request. I'm not sure how to fix this? Not sure if I missed something from the curl call?

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234

1 Answers1

0

I'll reply the same thing I always reply when someone is trying to debug network issues. Install wireshark, create a session with the traffic you want to mimic, then create another one with your own code. This will allow you to see exactly what is going on and which header are not transmitted correct.

Eric
  • 19,525
  • 19
  • 84
  • 147