首页 > 解决方案 > 在 C# 中使用 json POST 请求

问题描述

我正在尝试执行通过 Postman 处理的 POST 请求,但从代码完成时出现 400 错误。

我正在尝试从这里到达 POST 端点:http: //developer.oanda.com/rest-live-v20/order-ep/

这是我的代码,有什么看起来不正确还是我错过了什么?

public void MakeOrder(string UID)
    {
        string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
        string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
        using (WebClient client = new WebClient())
        {
            client.Headers.Add("Authorization", "Bearer 11699873cb44ea6260ca3aa42d2898ac-2896712134c5924a25af3525d3bea9b0");
            client.Headers.Add("Content-Type", "application/json");
            client.UploadString(url, body);
        }
    }

我对编码很陌生,如果它很简单,我很抱歉。

标签: c#jsonpost

解决方案


我建议您HttpClient通过 WebClient 使用。你可以在这里找到不同之处。

using (var httpClient = new HttpClient())
{

    string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
    string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
    var content = new StringContent(body, Encoding.UTF8, "application/json");
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTIzMDY0NTQsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ.c-3boD5NtOEhXNUnzPHGD4rY1lbEd-pjfn7C6kDPbxw");
    var result = httpClient.PostAsync(url, content).Result;
    var contents = result.Content.ReadAsStringAsync();
}

推荐阅读