在c#中使用json的POST请求

问题描述 投票:1回答:1

我试图做一个POST请求,我已经通过Postman得到了工作,但当我从代码中完成时,我得到一个400错误。

我试图从这里到达POST端点。http:/developer.oanda.comrest-live-v20order-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# json post
1个回答
0
投票

使用System.Net.Http.Net的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();
}

0
投票

我建议你使用 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();
}
© www.soinside.com 2019 - 2024. All rights reserved.