API Web Post Returns Invalid Content Type

Asked

Viewed 834 times

2

I am trying to send a POST request to a Web API.

If I do it for Postman, it works:

inserir a descrição da imagem aqui

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?

1 answer

2


just a hint, keep in memory the instance of your HttpClient, in his PostAsync you should inform only the relative path. Understand the reason by reading the following article: YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE

Furthermore, your code seems correct to me, normally I do as follows

public class WebApiProxy
{
    private static HttpClient Client;

    static Base()
    {
        // var cookieContainer = new CookieContainer();
        // var httpClientHandler = new HttpClientHandler();
        // httpClientHandler.CookieContainer = cookieContainer;
        // Client = new HttpClient(httpClientHandler);

        Client = new HttpClient();
        client.BaseAddress = new Uri(Constants.BaseUrl);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Constants.APIAuth)));
    }

    public async Task<Resposta> SendBilling(Billing billing)
    {
        var json = JsonConvert.SerializeObject(billing);
        var httpRequest = new HttpRequestMessage(HttpMethod.Post, Constants.RelativePath);
        httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
        using (var request = await Client.SendAsync(httpRequest))
        {
            if (request.IsSuccessStatusCode)
            {
                var responseJson = await request.Content.ReadAsStringAsync();
                var responseWrap = JsonConvert.DeserializeObject<Resposta>(responseJson);
                return responseWrap;
            }
        }
        return null;
    }
}

EDIT

Chatting with AP via Chat, we identified that the problem was poorly performed validation by API.

Httpclient sends together with Content-Type the CHARSET, such behavior is included in the protocol specification.: W3C

But the API did not behave as expected when receiving a Content-Type with CHARSET, thus ignoring the request.

As an outline solution, it was necessary to remove the charset of Content-Type.:

var content = new StringContent(json, Encoding.UTF8, "application/json"); 
content.Headers.ContentType.CharSet = string.Empty;
  • 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 the API is third party or its own?

  • 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...

  • https://chat.stackexchange.com/rooms/75001/perozzo-c-httpclient

Browser other questions tagged

You are not signed in. Login or sign up in order to post.