Home > Blockchain >  C# HTTPClient PostAsync does not send data
C# HTTPClient PostAsync does not send data

Time:06-17

I have the following code to send an HTTP request, but it does not transmit any packets (checked using Wireshark).

        var httpClient = new HttpClient();
        string uri = "http://"   IP   ":"   port   "/";

        var stringContent = new StringContent(xmlString, Encoding.UTF8, "application/xml");
        var respone = httpClient.PutAsync(uri, stringContent);

However, it transmits packet when I add:

respone.Wait(100);

Can you please help on how do get httpClient.PutAsync to work without the wait?

Thanks!

CodePudding user response:

As they already told you, you are using an asynchronous call so you have to wait until that action is solved to end your method/program.

Also, it's a good practice to use using statements for your httpClient and your content, so you free the memory once the code is executed. And maybe you'll want to react to the HTTP response. Try something like this:

            using (HttpClient httpClient= new HttpClient())
            {
                using (StringContent content = new StringContent(xmlString))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
                    HttpResponseMessage message = await httpClient.PutAsync(new Uri("http://"   IP   ":"   port   "/"), content).ConfigureAwait(false);
                    if (!message.IsSuccessStatusCode)
                    {
                         //For example log a failure
                        _logger.LogError($"HTTP unsuccess status code: {await message.Content.ReadAsStringAsync().ConfigureAwait(false)}");
                    }
                }
            }

CodePudding user response:

PutAsync is an async method that returns System.Threading.Tasks.Task<TResult> that is awaitable and should be awaited to call it asynchronous and get the result of it this code is the best way to call the method asynchronously and return its value NOTE: you better call it in Async method:

var respone = await httpClient.PutAsync(uri, stringContent);

if you insist on calling it synchronously, you can get the Result of Task,

which will cause your thread to block until the Result is available as @Heinzi answered this problem :

var respone = httpClient.PutAsync(uri, stringContent).Result;
  • Related