2
I am trying to send a POST request to a Web API.
If I do it for Postman, it works:
Now when I try to perform through the code, I get the following error:
{
"status": false,
"message": "Content Type Inválido. (Formato aceito: Content Type = \"application/json\" ",
"total": 0
}
I’ve tried that way:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Constants.APIV2);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Constants.APIAuth)));
string json = JsonConvert.SerializeObject(billing);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Constants.Billing);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
await client.SendAsync(request)
.ContinueWith(responseTask =>
{
var teste = responseTask.Result.Content.ReadAsStringAsync();
});
And of that:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Constants.APIV2);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Constants.APIAuth)));
string json = JsonConvert.SerializeObject(billing);
HttpResponseMessage response = await client.PostAsync(Constants.Billing, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync();
}
And unsuccessfully.
Any idea what I might be doing wrong?
Thank you so much for the tip! However my post keeps generating the same error. Your code is almost the same as my first example, the difference is that Httclient you create in another location.
– perozzo
@Perozzo the API is third party or its own?
– Tobias Mesquita
It’s third-party. It’s an integration API they’re deploying here in the company. The weird thing is that via Postman it works perfectly...
– perozzo
https://chat.stackexchange.com/rooms/75001/perozzo-c-httpclient
– Tobias Mesquita