Reputation: 31
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
Upvotes: 3
Views: 2234
Reputation: 780
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#
Upvotes: 2
Reputation: 81
Morning!
400 Bad request -
This just means there's something unsuitable with the request you're sending.
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?
Upvotes: 2