Wednesday, 1 November 2017

Simple C# .NET 4.5 HTTPClient Request Using Basic Auth

In this article I have created a C# method that connect and communicates with web apis and services using Basic Auth.


Step 1: Copy and paste the following method in your code file:
static void HTTP_POST(string targetUrl, string jsonData, string userName, string password)
        {
            var credentials = new NetworkCredential(userName, password);
            var handler = new HttpClientHandler { Credentials = credentials };

            using (var client = new HttpClient(handler))

            {
                var byteArray = Encoding.ASCII.GetBytes(userName + ":" + password);
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);

                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                using (HttpResponseMessage response = client.PostAsync(targetUrl, byteContent).Result)

                {
                    string result = response.Content.ReadAsStringAsync().Result;
                }
            }
        }
Step 2: You can use this method as following code:
  var postData = new
            {
                email_address = "test@gmail.com",
                email_type = "html",
                description = "test description"
            };
            HTTP_POST("https://yoururl.com", JsonConvert.SerializeObject(postData), "test", "pwd@123");

No comments:

Post a Comment