繁体   English   中英

c# 中的 json 的 POST 请求

[英]POST Request with json in c#

我正在尝试通过 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);
        }
    }

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

使用 System.Net.Http 中的 HttpClient:

using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

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");
       var result = httpClient.PostAsync(url, content).Result;
       var contents = result.Content.ReadAsStringAsync();
}

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

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM