HttpClient SendAsync method usage for POST request

Here is very basic example for usage of HttpClient for your REST calls.

public static async Task<string> UpdateUser(string endpoint, string accessToken, string displayName)
       {
           HttpClient client = new HttpClient();
           HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("POST"), endpoint);
           message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
           message.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
           List<KeyValuePair<string, string>> nameValueCollection = new List<KeyValuePair<string, string>>();
           nameValueCollection.Add(new KeyValuePair<string, string>("display_name", displayName));
           message.Content = new FormUrlEncodedContent(nameValueCollection);
           try
           {
               HttpResponseMessage httpResponseMessage = await client.SendAsync(message);
               httpResponseMessage.EnsureSuccessStatusCode();
               HttpContent httpContent = httpResponseMessage.Content;
               string responseString = await httpContent.ReadAsStringAsync();
               return responseString;
           }
           catch (Exception ex)
           {
               string errorType = ex.GetType().ToString();
               string errorMessage = errorType + ": " + ex.Message;
               throw new Exception(errorMessage, ex.InnerException);
           }
       }

Leave a Reply

Your email address will not be published. Required fields are marked *