CURL post request to C# post request

时间:2018-07-23 14:15:10

标签: c# http-post

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.

1 个答案:

答案 0 :(得分:2)

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

应该是:

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

此外,您的JSON似乎未正确转义。试试:

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

您还没有声明结果变量

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

基本上,您发布的示例甚至不应该编译...