c# - 在 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);
}
}
我对编码很陌生,如果它很简单,我很抱歉。
解决方案
我建议您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();
}
推荐阅读
- flutter - 术语“open”未被识别为 cmdlet 的名称
- python - 如何从熊猫的子类别中创建新列?
- python - 在 django 中设计通知系统的适当模式?
- python - 如何根据颜色跟踪精灵上的点
- javascript - 从 pug 中的 JSON 对象正确创建表
- html - 将表单数据转发到特定端口
- javascript - Gatsby `createPage` 正在生成具有相同数据的页面
- javascript - redux-starter-kit 的 createSlice 中的变异状态
- powershell - 安装 Sitecore 9.2 时出错 - 无法解析 [variable('XConnectSolr_Core.Root')]
- java - 如何将多个变量写入文本文件?