【问题标题】:Getting error 400 when I post a JSON data with HttpClient使用 HttpClient 发布 JSON 数据时出现错误 400
【发布时间】:2019-01-30 11:37:55
【问题描述】:

我正在尝试将 JSON 格式的数据发布到 API:

我的JSON 数据是:

{
    "itemData": {
                 "Name": "test",
                 "Priority": "High",
                 "SpecificContent": {},
                 "DeferDate": "2019-01-22T11:21:09.431Z",
                 "DueDate": "2019-01-22T11:21:09.432Z",
                 "Reference": "toto"
                }
           }

我的代码:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", mytoken);
    var res = client.PostAsync(MyURL,
      new StringContent(JsonConvert.SerializeObject(new { ItemData = new { Name = "toto", Priority = "High", SpecificContent = new { } } }),
        Encoding.UTF8, "application/json"));

    try
    {
        res.Result.EnsureSuccessStatusCode();
        MessageBox.Show(res.Result.EnsureSuccessStatusCode().ToString());
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
}

我有一个错误:

statusCode: 400 错误请求

我的代码有什么问题?

感谢您的帮助

【问题讨论】:

    标签: c# json post dotnet-httpclient


    【解决方案1】:

    早上好!

    400 错误请求 -

    这只是表示您发送的请求有一些不合适的地方。

    https://www.ionos.com/digitalguide/hosting/technical-matters/http-400-bad-request-finding-the-causes/

    我的第一个检查通常是确保您发送的对象与 API 端点所期望的数据完全相同:也许您可以向我们提供您正在调用的 API 的一些详细信息?

    【讨论】:

    • 我在这里调用 UIPATH API 成功的 curl : curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X -XSRF-TOKEN: token -d '{\"itemData":{\"Name":"toto",\"Priority":"High",\"SpecificContent":{}\\}\
    • 所以我尝试使用 JsonConvert.SerializeObject(new { ItemData = new { Name = "toto", Priority = "High", SpecificContent = new { } } } 发送相同的内容。但看起来这不是 API 所期望的数据。你能帮我吗?谢谢
    【解决方案2】:

    错误 400 表示请求错误。因此,您发布到的服务器期待您未发送的内容。使用 postman 之类的 HTTP 伪造工具来制作您需要的 HTTP 请求。了解所有细节后,将其转移到 C#

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 2019-06-22
      • 2019-05-03
      • 2016-12-27
      • 1970-01-01
      • 2021-11-22
      相关资源
      最近更新 更多