简体   繁体   中英

Getting error 400 when I post a JSON data with HttpClient

I'm trying to post data in JSON format to an API:

My JSON data is :

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

My code:

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

I have an error:

statusCode: 400 Bad request

What's wrong with my code?

Thanks for helping

An error 400 indicates a bad request. So the server you're posting to is expecting what you are not sending. Find out with a HTTP forgery tool like postman to craft the HTTP request you need. Once you know all the details, transfer it to C#

Morning!

400 Bad request -

This just means there's something unsuitable with the request you're sending.

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

My first check would normally be to make sure that the object your sending over is EXACTLY the same data as is expected by the API endpoint: Maybe you could provide us with some details of the API you're calling?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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