Ika
Ika

Reputation: 211

CURL post request to C# post request

Could you please help me to make a post request in c#. Here is curl:

curl -X POST https://api.test.com/call \
  -H "Content-Type: application/json" \
  -H "Authorization: Token token=YOUR_TOKEN" \
  -d '{"amount":10.00, "id":"123", "customer":{"external_id":"100"}, "receiver":{"external_id":"200"}}'

I tried doing this:

string myJson = "{"amount":10.00, "id":"123", "customer":{"external_id":"100"}, "receiver":{"external_id":"200"}}";
    using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://api.test.com");                    
                    client.DefaultRequestHeaders.Add("APIAccessToken", "myToken");               
                    var content = new StringContent(myJson, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync("https://api.test.com/call/", content);
                    resultContent = await response.Content.ReadAsStringAsync();
                }

But getting bad request response 400 Error. I am new to this, will appreciate your help.

Upvotes: 0

Views: 296

Answers (1)

Stevo
Stevo

Reputation: 1434

var response = await client.PostAsync("https://api.test.com/call/", content);

Should be:

var response = await client.PostAsync("call", content);

Also, looks like your JSON isn't properly escaped. Try:

string myJson = "{\"amount\":10.00, \"id\":\"123\", \"customer\":{\"external_id\":\"100\"}, \"receiver\":{\"external_id\":\"200\"}}";

And you haven't declared your result variable

// Missing var
var resultContent = await response.Content.ReadAsStringAsync();

Basically, the example you posted shouldn't even compile...

Upvotes: 2

Related Questions