How to post data using HttpClient

In this post, I will show you how to post data to web API using HttpClient.

  private static async Task PostJSON()
        {
            HttpClient httpClient = new HttpClient();
            HttpContent content = new StringContent(@"{ ""Username"": """ + "etc." + @"""}");
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpResponseMessage response =
                await httpClient.PostAsync("http://myapi.com/authentication", content);
            string statusCode = response.StatusCode.ToString();
        }

        /// <summary>
        /// Post Key/Value
        /// </summary>
        /// <returns></returns>
        private static async Task Post()
        {
            HttpClient client = new HttpClient();

            var values = new Dictionary<string, string>();
            values.Add("author", "santosh");
            values.Add("text", "singh");
            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("http://localhost:4500/quote", content);
        }

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post