Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post an empty body to REST API via HttpClient

People also ask

Can HttpContent be null?

Net. Http in version 5.0. 0.0 has still no nullable HttpContent parameter, so null should be not allowed.

What is HttpClient in REST API?

Apache HttpClient is a robust and complete solution Java library to perform HTTP operations, including RESTful service. In this tutorial, we show you how to create a RESTful Java client with Apache HttpClient, to perform a “GET” and “POST” request. Note.

How do I use HttpClient Getasync?

Using SendAsync, we can write the code as: static async Task SendURI(Uri u, HttpContent c) { var response = string. Empty; using (var client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage { Method = HttpMethod. Post, RequestUri = u, Content = c }; HttpResponseMessage result = await client.


Use StringContent or ObjectContent which derive from HttpContent or you can use null as HttpContent:

var response = await client.PostAsync(requestUri, null);

Did this before, just keep it simple:

Task<HttpResponseMessage> task = client.PostAsync(url, null);

Have found that:

Task<HttpResponseMessage> task = client.PostAsync(url, null);

Adds null to the request body, which failed on WSO2. Replaced with:

Task<HttpResponseMessage> task = client.PostAsync(url, new {});

And worked.


To solve this problem, use this example:

   using (var client = new HttpClient())
            {
                var stringContent = new StringContent(string.Empty);
                stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                var response = client.PostAsync(url, stringContent).Result;
                var result = response.Content.ReadAsAsync<model>().Result;
            }